我得到了这个程序,它创建了一个孤立的进程,但是我不太理解它的控制流,因此它给出的输出:
#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秒。并再次执行‘子进程之类的’。再一次看到“父母完成了.”的事情。
即使这个问题看起来很傻,也请帮帮我。
发布于 2014-10-08 01:00:18
fork()的调用复制父进程及其整个状态并执行它,创建子进程。父进程和子进程现在同时运行。fork()接收0作为返回值,因此它休眠10秒。( b)父进程接收子进程的pid作为来自fork()的返回值,该值当然不等于0;因此父进程不会休眠10秒。"the child process pid is 2575 parent pid 1922"。然后,父进程会遇到睡眠20秒的指令,并这样做。"The child process pid is 2576 parent pid 2575"。在此之后,子进程将遇到睡眠20秒的指令,并这样做。"Process 2575 is done its Parent pid 1922...",然后退出。"Process 2576 is done its Parent pid 1...",然后退出。但是,为什么父母pid 1,即使是在2575之前?因为父进程已经退出,导致子进程被init进程孤立,init进程的pid值为1。发布于 2014-10-08 00:47:17
父母和孩子之间唯一不同的地方是sleep(10)。因此,两个printf和sleep(20)将同时由子和父执行。但是,由于有了sleep(10),子程序的printfs将在父文件对应的printfs之后延迟10秒。
也就是说,第一个printf是误导性的。它应该说
printf( "my pid is %d and my parent's pid is %d\n", getpid(), getppid() );在示例输出中,子变量为pid 2576,父值为2575,祖父母为pid 1922。祖父母是启动程序的shell进程。
https://stackoverflow.com/questions/26247409
复制相似问题