子进程执行fork调用前写的语句

Use*_*007 3 c fork ipc

我正在我的代码中创建子进程。当我调用 fork() 时,子进程应该从下一条语句开始执行,但在我的代码中,子进程在 fork 调用之前执行语句。

#include<stdio.h>
int main()
{
int pid;
FILE *fp;
fp = fopen("oh.txt","w");
fprintf(fp,"i am before fork\n");
pid = fork();
        if(pid == 0)
        {
                fprintf(fp,"i am inside child block\n");
        }
        else{
                fprintf(fp,"i inside parent block\n");
        }
fprintf(fp,"i am inside the common block to both parent and child\n");
fclose(fp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出

输出:

i am before fork
i inside parent block
i am inside the common block to both parent and child
i am before fork
i am inside child block
i am inside the common block to both parent and child
Run Code Online (Sandbox Code Playgroud)

“i am before fork”这一行应该在文件中写一次,但孩子和父母写了两次。为什么会这样?

谢谢你。

nne*_*neo 5

这可能是一个缓冲问题。fprintf不会立即写入文件,而是缓冲输出。当你fork,你最终得到缓冲区的两个副本。

尝试fflush(fp)在 fork 之前做一个,看看是否能解决问题。