13

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?

4

1 回答 1

30

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

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);

当然,这一切都毫无意义。如果父母只是无视SIGCHLD,孩子们就会默默收割,不会变成僵尸。

引用TLPI

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

所以这样的事情应该为你解决问题:

signal(SIGCHLD, SIG_IGN); /* Silently (and portably) reap children. */
于 2011-08-24T07:22:46.570 回答