How can I handle SIGCHLD?

最后都变了- 提交于 2019-11-26 09:39:57

问题


I need to handle SIGCHLD properly. How can I use it with my existing code? at the moment I cant wait for the child process unless I use 0 instead of 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 sleep then parent is executed 1st.. why?


回答1:


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.

Quoting 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.

So something like this should do the trick for you:

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


来源:https://stackoverflow.com/questions/7171722/how-can-i-handle-sigchld

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