我正在我的代码中创建子进程。当我调用 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;
}
这是我得到的输出
输出:
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
“我在 fork 之前”这一行应该在文件中写入一次,但由孩子和父母写入两次。为什么会这样?
谢谢你。