[英]What is the use of ignoring `SIGCHLD` signal with `sigaction(2)`?
It turns out that we can prevent appearing of a zombie process (ie the one whose parent doesn't wait()
for it to _exit()
) by specifying SIGCHLD
signal to be ignored with sigaction()
by its parent.事实证明,我们可以通过指定
SIGCHLD
信号被其父SIGCHLD
用sigaction()
忽略来防止出现僵尸进程(即,其父进程不wait()
它到_exit()
)。 However, it seems like SIGCHLD
is ignored by default anyway.但是,无论如何,默认情况下似乎都忽略了
SIGCHLD
。 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;
}
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. SIGCHLD
的默认行为是丢弃信号,但子进程将保持为僵尸进程,直到父进程调用wait()
(或变体)来获取其终止状态。
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.但是,如果您使用
SIG_IGN
的处置显式调用sigaction()
,则会导致它不会将孩子变成僵尸——当孩子退出时,它会立即被收割。 See https://stackoverflow.com/a/7171836/1491895见https://stackoverflow.com/a/7171836/1491895
The POSIX way to get this behavior is by calling sigaction
with handler = SIG_DFL
and flags
containing SA_NOCLDWAIT
.获得此行为的 POSIX 方法是使用
handler = SIG_DFL
和包含SA_NOCLDWAIT
flags
调用sigaction
。 This is in Linux since 2.6.从 2.6 开始,这是在 Linux 中。
The confusion is that you seem to be asuming that " SIGCHLD
is ignored by default" means that the default disposition of the signal is SIG_IGN
.令人困惑的是,您似乎假设“默认情况下忽略
SIGCHLD
”意味着信号的默认处置是SIG_IGN
。
That's not the case.事实并非如此。 The default disposition is
SIG_DFL
.默认配置是
SIG_DFL
。 When you set it to SIG_IGN
you're actually changing it.当您将其设置为
SIG_IGN
您实际上是在更改它。 And after you've set it as SIG_IGN
, you can revert it back to SIG_DFL
, getting the original behavior again.在您将其设置为
SIG_IGN
,您可以将其恢复为SIG_DFL
,再次获得原始行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.