C语言 我该如何处理 SIGCHLD?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7171722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:27:48  来源:igfitidea点击:

How can I handle SIGCHLD?

csigchld

提问by kanoz

I need to handle SIGCHLDproperly. How can I use it with my existing code? at the moment I cant wait for the child process unless I use 0instead of WNOHANG|WUNTRACED.

我需要SIGCHLD妥善处理。如何将它与我现有的代码一起使用?目前我不能等待子进程,除非我使用0而不是WNOHANG|WUNTRACED.

status = 0; 
pid_t child, endID;

if(amp == 1)
        signal( SIGCHLD, SIG_IGN ); 

child = fork(); 

if (child  <  0) {    
        perror("fork() error\n");
        exit(EXIT_FAILURE);

} else if (child == 0) { 
        // do sth here
        perror("error\n");

} else { 
        //sleep(1)

If I remove sleepthen parent is executed 1st.. why?

如果我删除sleep然后父级被执行 1st.. 为什么?

回答by cnicutar

Here is a start (but read below):

这是一个开始(但请阅读下文):

static void
child_handler(int sig)
{
    pid_t pid;
    int status;

    /* EEEEXTEERMINAAATE! */
    while((pid = waitpid(-1, &status, WNOHANG)) > 0)
        ;
}

/* Establish handler. */
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = child_handler;

sigaction(SIGCHLD, &sa, NULL);


Of course, this is all pointless. If the parent simply ignores SIGCHLD, the children are silently reaped and won't turn into zombies.

当然,这都是没有意义的。如果父母不理会SIGCHLD,孩子会默默地收获,不会变成僵尸。

Quoting TLPI:

引用TLPI

Explicitly setting the disposition of SIGCHLD to SIG_IGN causes any child process that subsequently terminates to be immediately removed from the system instead of being converted into a zombie.

将 SIGCHLD 的处置显式设置为 SIG_IGN 会导致随后终止的任何子进程立即从系统中删除,而不是转换为僵尸进程。

So something like this should do the trick for you:

所以像这样的事情应该对你有用:

signal(SIGCHLD, SIG_IGN); /* Silently (and portably) reap children. */