Detach child process from parent

随声附和 提交于 2019-12-21 17:16:46

问题


When a child process forked from a parent dies, it still exists to some extent and is left in a zombie state, until it is reaped from a wait() call.

Is is possible to detach this parent-child relationship and have the children be automatically reaped? Maybe orphan off the child to init, or something?

Possible use case: Creating a lot of fire-and-forget processes in a long-lived program, without "holding" on to an increasing list of zombie PIDs that cannot be recycled by the OS.


回答1:


Per the POSIX _exit() documentation:

If the parent process of the calling process has set its SA_NOCLDWAIT flag or has set the action for the SIGCHLD signal to SIG_IGN:

  • The process' status information (see Status Information), if any, shall be discarded.

  • The lifetime of the calling process shall end immediately. If SA_NOCLDWAIT is set, it is implementation-defined whether a SIGCHLD signal is sent to the parent process.

  • If a thread in the parent process of the calling process is blocked in wait(), waitpid(), or waitid(), and the parent process has no remaining child processes in the set of waited-for children, the wait(), waitid(), or waitpid() function shall fail and set errno to [ECHILD].

Otherwise:

  • Status information (see Status Information) shall be generated.

  • The calling process shall be transformed into a zombie process. Its status information shall be made available to the parent process until the process' lifetime ends.

  • ...

In short, to prevent child processes from becoming zombie processes, the simplest way is to call sigignore( SIGCHLD );

UPDATE

That does impact the ability to wait for any child process, which may not be desired. The setsid() library function allows a process to disassociate itself from its parent:

pid_t child = fork();
if ( ( pid_t ) 0 == child )
{
    int rc = setsid();

    rc = execv(...);
}
else ...

The disassociated child process doesn't create a zombie nor send SIGCHLD to the parent process on my installed instance of Solaris 11.2.

This is an abbreviated daemonization of a "fire-and-forget" child process, only doing what is necessary to prevent creating a zombie or sending SIGCHLD to the parent process. For a much fuller daemonization procedure, see Linux daemonize



来源:https://stackoverflow.com/questions/46621463/detach-child-process-from-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!