我对fork(),父级和子级进程不熟悉,并且在理解我编写的代码背后的逻辑时遇到了一些困难,但未达到我的预期。这是我所拥有的:
int main (int argc, char** argv)
{
FILE *fp_parent;
FILE *fp_child;
fp_parent = fopen ("parent.out","w");
fp_child = fopen ("child.out","w");
int test_pid;
printf ("GET HERE\n");
fprintf (fp_parent,"Begin\n"); // MY CONCERN
for (int i = 0; i < 1; i++) //for simplicity, just fork 1 process.
{ // but i want to fork more processes later
test_pid = fork();
if(test_pid < 0)
{
printf ("ERROR fork\n");
exit (0);
}
else if(test_pid == 0) // CHILD
{
fprintf(fp_child,"child\n");
break;
}
else //PARENT
{
fprintf(fp_parent,"parent\n");
}
}
fclose(fp_parent);
fclose(fp_child);
}
因此,以上代码的输出为:
to stdout: GET HERE
in parent.out:
Begin
parent
Begin
in child.out:
child
我主要担心的是,我不太了解为什么“ Begin”被两次写入parent.out。如果我完全删除了for循环,则只写一个“ Begin”(预期)。
因此,我认为这是因为fork()所致,我肯定错过或不了解其背后的逻辑。你们能帮我解释一下吗?
我的计划是能够在parent.out的for循环之前写一些东西,并在parent.out的for循环期间写一些东西。子进程将写入child.out。
最佳答案
在C语言中,使用FILE
结构的输入/输出操作在用户进程级别得到缓冲。在您的情况下,您已写入fp_parent
的输出实际上并未写入磁盘,并且在fork
时保存在本地缓冲区中。 fork
创建整个过程的副本,包括包含Begin
的缓冲区,这就是为什么它在文件中出现两次的原因。尝试将fflush(fp_parent);
放在fork
之前。这将刷新缓冲区,脏行将从文件中消失。