linux printf和fork()问题小结

总结如下:

    printf("father begin");
  
      pid_t pid;
      pid = fork();
      if(pid > 0)
      {
          while(1)
          {
              printf("father out");
              sleep(1);
          }
      }
      else if(pid == 0)
      {
          while(1)
          {
              printf("child out 
" );
              sleep(1);
         }
     }
     

需要注意的是printf是c标准库函数 运行在用户态 拥有缓冲区     是行缓冲 遇到 或者行满或者类似getchar scanf对缓冲区读操作的函数会刷新缓冲区或者进程运行结束才会自动刷新缓冲区

一般的打开文件时全缓冲   linux终端也是行缓冲

fork()会赋值主进程的所有数据 包括缓冲区 因此会发生一些你预料之外的结果 和你想象中的不一样

原文地址:https://www.cnblogs.com/huoxl/p/4234996.html