我正在尝试构建一个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