【发布时间】:2015-11-26 16:06:37
【问题描述】:
我正在尝试学习 UNIX 编程,遇到了一个关于 fork() 的问题,我无法解释以下 2 个程序的输出。
我知道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)?
标签: c operating-system buffer fork system-calls