[英]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;
}
在第一个printf()
之后,它没有刷新输出缓冲区。
如果此程序的输出重定向到文件,则输出将被块缓冲,则此printf()
的输出可能会也可能不会写入输出文件,因此,输出文件可能为五行或四行(实际上,其中大多数是五行)。
添加一个fflush(stdout);
在第一个printf()
可以解决此问题。
父进程在子进程之前终止。
在这种情况下,在该程序的数千次运行中一次或两次,子进程的输出丢失,输出文件只有三行。 但是,在添加fflush()
之后,输出文件应为四行。
我真的不明白为什么会这样,或者是否正确。 但幸运的是,它很容易修复。 添加一个wait(NULL);
在第三个printf()
之后。
这是来自Art的一些非常有用的解释:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.