【问题标题】:buffering mechanism when fork is used in c [duplicate]在c中使用fork时的缓冲机制[重复]
【发布时间】:2012-07-05 23:07:56
【问题描述】:

可能重复:
Working of fork() in linux gcc
Why does this code print two times?

我想知道下面代码输出背后的原因:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
   FILE *fp;
   int n;
   printf("%d",45);
   //fflush(stdout);
   if((n=fork())>0){
      printf("in parent\n");  
      exit(0);
   }
   else if(n==0)
       printf("%d",45);
}

输出

45inparent
4545

如果我使用 fflush,那么 输出

45inparent
45

另外,我是在linux平台上运行的

【问题讨论】:

标签: c file-io


【解决方案1】:

子进程继承打开的文件描述符(在这种情况下为标准输出)和与之关联的缓冲区。

  • 如果在fork之前不刷新缓冲区,那么缓冲区的内容就会重复(包括“45”),“45”会打印两次。
  • 如果在 fork 之前刷新,缓冲区会被清空,并且子进程会获得缓冲区的空副本,因此父进程只会打印一次“45”。

【讨论】:

    【解决方案2】:

    第一个 printf() 将字符串 45 写入内存缓冲区。

    在 fork() 调用期间,缓冲区实际上在子进程中复制,因此父进程和子进程在 stdout 的缓冲区中都有45

    在两个进程中刷新该缓冲区将写入两次45

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-01
      • 2011-08-23
      • 2023-03-28
      • 2013-09-11
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多