繁体   English   中英

一个简单的fork程序

[英]a simple fork program

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
  pid_t child_pid;
  printf ("the main program process ID is %d\n", (int) getpid());
  child_pid = fork () ;
  if (child_pid != 0) 
  {
    printf ("this is the parent process, with id %d\n", (int) getpid ());
    printf ("the child's process ID is %d\n",(int) child_pid );
  }
  else
    printf ("this is the child process, with id %d\n", (int) getpid ());
  return 0;
}

我编写了一个简单的fork程序来创建一个进程,当我运行该程序时,输出如下:

the main program process ID is 3322
this is the child process , with ID 0

现在,我的观点是,为什么不执行if块,在父进程中fork()的返回值不等于0所以为什么我没有获得if块的任何输出?

以下代码至少有两个问题:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
    pid_t child_pid;
    printf ("the main program process ID is %d\n", (int) getpid());
    child_pid = fork () ;
    if (child_pid > 0) 
    {
        printf ("this is the parent process, with id %d\n", (int) getpid ());
        printf ("the child's process ID is %d\n",(int) child_pid );
    }
    else if (child_pid == 0)
        printf ("this is the child process, with id %d\n", (int) getpid ());
    else
        printf ("fork failed\n");

    return 0;
}
  1. 在第一个printf()之后,它没有刷新输出缓冲区。

    如果此程序的输出重定向到文件,则输出将被块缓冲,则此printf()的输出可能会也可能不会写入输出文件,因此,输出文件可能为五行或四行(实际上,其中大多数是五行)。

    添加一个fflush(stdout); 在第一个printf()可以解决此问题。

  2. 父进程在子进程之前终止。

    在这种情况下,在该程序的数千次运行中一次或两次,子进程的输出丢失,输出文件只有三行。 但是,在添加fflush()之后,输出文件应为四行。

    我真的不明白为什么会这样,或者是否正确。 但幸运的是,它很容易修复。 添加一个wait(NULL); 在第三个printf()之后。


这是来自Art的一些非常有用的解释:

  1. POSIX强制在派生后子进程中的文件描述符指向相同的文件描述(文件描述与文件描述符不同)。 文件描述包含(尤其是)文件偏移量。 printf最终将进行写操作以写出其输出,并保证写操作可以原子地更新文件偏移并写出数据。 因此,只要不寻找该程序,就可以在派生程序中重定向输出是安全的(您不应该在stdout和printf上这样做)。

  2. 前面的注释中不适合的引用: 文件描述fork

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM