我正在尝试学习UNIX编程,并遇到了一个关于fork()
的问题,我无法解释下面两个程序的输出。
我知道fork()
会创建一个与当前运行进程完全相同的进程,但它从哪里开始呢?例如,如果我有以下这两个程序,它们的输出将是什么,它是如何工作的?
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main (int argc, char **argv)
{
int retval;
printf ("This is most definitely the parent process\n");
// now here fork will create a child process
// i need to know from which line child process starts execution
retval = fork ();
printf ("Which process printed this?\n");
return (0);
}
关于子进程执行,上面的程序和下面的程序有何不同:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main (int argc, char **argv)
{
int retval;
printf ("This is most definitely the parent process\n");
fflush (stdout);
// how does fflush change the output of above program and why ?
// even though no string operations are being used
retval = fork ();
printf ("Which process printed this?\n");
return (0);
}
我认为他们都应该打印:
This is most definitely the parent process
Which process printed this?
Which process printed this?
但是第一个问题是打印:
This is most definitely the parent process
Which process printed this?
This is most definitely the parent process
Which process printed this?
fork(2)
的man手册吗? - SirPython