【发布时间】:2014-10-08 00:29:02
【问题描述】:
我有这个程序可以创建一个孤立进程,但我不太了解它的控制流以及它给出的输出:
#include<stdio.h>
#include<unistd.h>
int main()
{
pid_t p;
/* create child process */
p=fork();
if(p==0) {
/* fork() returns Zero to child */
sleep(10);
}
printf("The child process pid is %d parent pid %d\n", getpid(), getppid());
/*parent/child waits for 20 secs and exits*/
sleep(20);
printf("\nProcess %d is done its Parent pid %d...\n", getpid(), getppid());
return 0;
}
输出:
shiv@ubuntu:~/ds/unix$ ./a.out
The child process pid is 2575 parent pid 1922
The child process pid is 2576 parent pid 2575
Process 2575 is done its Parent pid 1922...
shiv@ubuntu:~/ds/unix$
Process 2576 is done its Parent pid 1...
所以它首先生成“子进程……”,然后休眠 10 秒。并再次执行 'child process blah blah' 。再次看到“父母已经完成......”的事情发生了
即使这个问题看起来很傻,请帮助我。
【问题讨论】:
-
请解释一下这个程序是如何工作的?
-
这个程序的哪一部分你不明白?
-
我不明白,在执行程序时,第一个在 if 语句之后给出第一行,然后休眠 10 秒,然后再次创建一个新的子节点,再次休眠 10 秒,然后执行第二个 printf 语句类似的方式。