简体   繁体   English

如何以一种不需要收割孩子的方式进行分叉过程

[英]How to forking process in a way such that reaping the child isn't neccessary

I seem to have a vague memory that some facility in Linux exists that allows one to fork() a process in such a way that the child is automatically reaped by the system without a zombie being created. 我似乎有一个模糊的记忆,Linux中的某些工具存在,它允许一个fork()一个进程,以便系统自动收集子进程而不创建僵尸。 What is this mechanism? 这个机制是什么? Or is my memory just wrong? 还是我的记忆错了?

The portable way to do this is to double-fork: 这样做的便携方式是双叉:

pid = fork();
if (pid>0) {
    int status;
    while (waitpid(pid, &status, 0) && !WIFEXITED(status) && !WIFSIGNALED(status));
    if (WIFSIGNALED(status) || WEXITSTATUS(status)) goto error;
} else if (!pid) {
    pid = fork();
    if (pid) _exit(pid<0);
    else {
        // do child work here
        _exit(0);
    }
} else goto error;

我在考虑Glib的g_spawn_ *方法,除非你指定你不想要那个默认行为,否则它会自动收割孩子。

You can ignore SIGCHLD so it's doesn't create zombie ;) 您可以忽略SIGCHLD,因此它不会创建僵尸;)

signal(SIGCHLD, SIG_IGN);

doc here: http://man7.org/linux/man-pages/man2/sigaction.2.html doc在这里: http//man7.org/linux/man-pages/man2/sigaction.2.html

This can also be done via prctl() 这也可以通过prctl()来完成

prctl(PR_SET_PDEATHSIG, SIGTERM);

The above line inserted in the child process can cause it's termination when the parent process is dead. 插入到子进程中的上述行可能导致父进程死亡时终止它。 This can also work when any sub-reapers die(after they parent the child process), and if you need it's actual parent's death to kill the child process, then store the parent's pid before fork() and check it in the child process. 这也适用于任何子收割者死亡(在父子进程之后),如果您需要实际的父死亡来杀死子进程,那么在fork()之前存储父进程的pid并在子进程中检查它。

if (getppid() != parent_pid_before_fork) exit(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM