我需要正确处理SIGCHLD.如何在现有代码中使用它.目前我不能等待子进程,除非我使用0而不是WNOHANG | WUNTRACED. status = 0; pid_t child, endID; if(amp == 1) signal( SIGCHLD, SIG_IGN ); child = fork(); if (child 0
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)
如果我删除睡眠然后父亲被执行第一个…为什么?
这是一个开始(但在下面阅读):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:
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.
所以像这样的东西应该为你做的伎俩:
signal(SIGCHLD, SIG_IGN); /* Silently (and portably) reap children. */