问题描述
事实证明,我们可以通过指定来防止出现僵尸进程(即,其父进程没有 wait()
等待它到 _exit()
)SIGCHLD
信号被其父级用 sigaction()
忽略.然而,似乎 SIGCHLD
在默认情况下被忽略.这是怎么回事?
It turns out that we can prevent appearing of a zombie process (i.e. the one whose parent doesn't wait()
for it to _exit()
) by specifying SIGCHLD
signal to be ignored with sigaction()
by its parent. However, it seems like SIGCHLD
is ignored by default anyway. How come does this work?
int main (void) {
struct sigaction sa;
sa.sa_handler = SIG_IGN; //handle signal by ignoring
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGCHLD, &sa, 0) == -1) {
perror(0);
exit(1);
}
int pid = fork();
if (pid == 0) { //child process
_exit(0);
}
do_something(); //parent process
return 0;
}
推荐答案
SIGCHLD
的默认行为是丢弃信号,但是子进程保持僵尸进程直到父进程调用 wait()
(或变体)以获取其终止状态.
The default behavior of SIGCHLD
is to discard the signal, but the child process is kept as a zombie until the parent calls wait()
(or a variant) to get its termination status.
但是如果你显式地调用带有 SIG_IGN
的 sigaction()
,这会导致它不会把孩子变成僵尸——当孩子退出时它会被收割立即地.请参阅https://stackoverflow.com/a/7171836/1491895
But if you explicitly call sigaction()
with the disposition SIG_IGN
, that causes it not to turn the child into a zombie -- when the child exits it is reaped immediately. See https://stackoverflow.com/a/7171836/1491895
获得此行为的 POSIX 方法是通过使用 handler = SIG_DFL
和包含 SA_NOCLDWAIT
的 flags
调用 sigaction
.这是从 2.6 开始的 Linux.
The POSIX way to get this behavior is by calling sigaction
with handler = SIG_DFL
and flags
containing SA_NOCLDWAIT
. This is in Linux since 2.6.
这篇关于使用“sigaction(2)"忽略“SIGCHLD"信号有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!