【问题标题】:Child process executes statements written before fork call子进程执行fork调用之前编写的语句
【发布时间】:2013-02-05 17:41:42
【问题描述】:

我正在我的代码中创建子进程。当我调用 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 之前”这一行应该在文件中写入一次,但由子级和父级写入两次。 为什么会这样?

谢谢。

【问题讨论】:

  • 在分叉前添加fflush(fp)

标签: c fork ipc


【解决方案1】:

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

在分叉前尝试fflush(fp) 看看是否能解决问题。

【讨论】:

    【解决方案2】:

    我猜这是因为您使用fprintf 打印,它被缓冲但不打印,然后在刷新缓冲区时在子进程中打印。

    【讨论】:

      猜你喜欢
      • 2012-08-15
      • 1970-01-01
      • 2016-03-02
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      相关资源
      最近更新 更多