【发布时间】:2014-10-11 08:14:52
【问题描述】:
我是 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
我主要担心的是我不太明白为什么“开始”会被写入 parent.out 两次。如果我完全删除了 for 循环,那么只会写入一个预期的“Begin”。
所以我认为这是因为 fork() 而我肯定错过或不理解它背后的一些逻辑。各位大神能帮我解释一下吗?
我的计划是能够在 parent.out 的 for 循环之前写一些东西,并在 parent.out 的 for 循环期间写一些东西。子进程将写入 child.out。
【问题讨论】:
标签: c process fork file-descriptor