我正在嘗試構建一個C程序,其中父級創建一個可用的源數組,然後爲了做某件事而分叉一些孩子。在這個階段,孩子們使用父母的「可用」數組創建一個數組,並使用他們剛剛創建的數組創建一個數組。分叉時的Printf行爲
這是我的代碼:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
pid_t wpid;
int i = 0;
int j = 0;
int status = 0;
int sources = 3;
int children = 3;
int *available = malloc(sources * sizeof(int));
for (i = 0; i < sources; i++)
available[i] = 20;
for (i = 0; i < children; i++)
{
pid_t pid = fork();
if (pid == 0)
{
// kid gets here
srand(getpid());
printf("Kid %d created!\n", getpid());
int *total = malloc(sources * sizeof(int));
int *request = malloc(sources * sizeof(int));
for (j = 0; j < sources; j++){
total[j] = rand() % (available[j]/2);
printf("Kid(%d): Source(%d) = %d\n", getpid(), j, total[j]);
}
for (j = 0; j < sources; j++){
request[j] = rand() % total[j];
printf("REQUEST: Kid(%d): Source(%d) = %d\n", getpid(), j, request[j]);
}
printf("==============================================================\n");
free(total);
free(request);
exit(0);
}
// parent gets here
sleep(1); // readable reasons
}
while ((wpid = wait(&status)) > 0);
free(available);
return 0;
}
問題
的問題是,有時,當我運行這個程序,我沒有得到我的終端所有的印刷品。例如,第二個循環應該正好打印3次REQUEST: blabla
,但有時它只打印兩次或根本不打印。
我試過
1)根據這個帖子printf anomaly after "fork()",「當你的程序的輸出去一個終端(屏幕),它是緩衝線」。但是我的所有照片最後都有'\ n',所以我不應該對printf的緩衝有任何問題。
2)每次打印後嘗試'fflush(stdout)'。
3)試圖使用fprintf打印到stderr。
那麼爲什麼有些打印不出現?
您鏈接的異常會影響在** fork之前**打印的東西,而不是之後。 – Barmar
注意:在編程中「孩子們」仍然被稱爲「孩子」,老兄! – Olaf
任何有用的答案? ^^ – matrix