Unix 在双叉中,为什么可以';在子项退出之前是否先退出子项?
双叉 在我的理解中,当一个进程想要分叉一个后台进程时,使用双分叉,但是1。它不想等待它和2。后台进程应该在退出后重新启动Unix 在双叉中,为什么可以';在子项退出之前是否先退出子项?,unix,fork,Unix,Fork,双叉 在我的理解中,当一个进程想要分叉一个后台进程时,使用双分叉,但是1。它不想等待它和2。后台进程应该在退出后重新启动 #include "apue.h" #include <sys/wait.h> int main(void) { pid_t pid; if ((pid = fork()) < 0) { err_sys("fork error"); } else if (pid == 0) { /* first ch
#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
pid_t pid;
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* first child */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid > 0)
exit(0); /* parent from second fork == first child */
/*
* We're the second child; our parent becomes init as soon
* as our real parent calls exit() in the statement above.
* Here's where we'd continue executing, knowing that when
* we're done, init will reap our status.
*/
sleep(2);
printf("second child, parent pid = %ld\n", (long)getppid());
exit(0);
}
if (waitpid(pid, NULL, 0) != pid) /* wait for first child */
err_sys("waitpid error");
/*
* We're the parent (the original process); we continue executing,
* knowing that we're not the parent of the second child.
*/
exit(0);
}
因此,double fork只需要父进程等待子进程,子进程应该在fork孙子进程之后立即退出,孙子进程作为后台进程负责实际任务
上下文
根据APUE的这段摘录,孙子睡2秒钟,以确保其父母(孩子)在离开之前离开,这样它将成为孤儿,init将照顾它,并在它离开时收获它
#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
pid_t pid;
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* first child */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid > 0)
exit(0); /* parent from second fork == first child */
/*
* We're the second child; our parent becomes init as soon
* as our real parent calls exit() in the statement above.
* Here's where we'd continue executing, knowing that when
* we're done, init will reap our status.
*/
sleep(2);
printf("second child, parent pid = %ld\n", (long)getppid());
exit(0);
}
if (waitpid(pid, NULL, 0) != pid) /* wait for first child */
err_sys("waitpid error");
/*
* We're the parent (the original process); we continue executing,
* knowing that we're not the parent of the second child.
*/
exit(0);
}
#包括“apue.h”
#包括
int
主(空)
{
pid_t pid;
如果((pid=fork())<0){
err_系统(“分叉错误”);
}如果(pid==0){/*第一个子项*/
如果((pid=fork())<0)
err_系统(“分叉错误”);
否则,如果(pid>0)
退出(0);/*第二个分支的父级==第一个子级*/
/*
*我们是第二个孩子,我们的父母很快就变成了第一个孩子
*正如我们真正的父对象在上面的语句中调用exit()。
*这是我们继续执行的地方,知道什么时候
*我们完成了,init将获得我们的地位。
*/
睡眠(2);
printf(“第二个子,父pid=%ld\n”,(长)getppid());
出口(0);
}
if(waitpid(pid,NULL,0)!=pid)/*等待第一个子项*/
err_sys(“waitpid错误”);
/*
*我们是父进程(原始进程);我们继续执行,
*知道我们不是第二个孩子的父母。
*/
出口(0);
}
问题
为什么孙子进程需要睡眠2秒?假设它在子进程退出之前退出,当子进程根据退出时,它仍然会被收获,并且父进程仍然不需要处理它
这不符合使用双叉的最初目标吗?本示例的目的是演示孙子的父进程在其原始父进程退出后成为进程1(init) 为了证明孙子的父进程变为进程1,孙子调用
getppid
并打印结果
getppid
,则getppid
返回的内容不是pid 1getppid
,则getppid
返回1示例程序的目的是实现#2。因此,在孙子调用
getppid
之前,它需要确保原始父级已退出。它通过调用孙子中的sleep(2)
来实现这一点
在一个真实的程序中,孙子不会睡在那里。它只会做它的工作
由于这是一个玩具程序,孙辈没有真正的工作要做