忽略带有sigaction(2)的SIGCHLD信号的用途是什么? [英] What is the use of ignoring `SIGCHLD` signal with `sigaction(2)`?

查看:152
本文介绍了忽略带有sigaction(2)的SIGCHLD信号的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实证明,通过指定要被其父级使用sigaction()忽略的SIGCHLD信号,我们可以防止出现僵尸进程(即其父级不是wait()的父级). .但是,看起来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方法是通过将sigactionhandler = SIG_DFLflags包含SA_NOCLDWAIT一起调用.从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信号的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆