子进程终止时了解SIGCHLD

时间:2022-02-15 21:01:48

I am not able to understand the output for the following program. I observed that after the child process returns, parent process is not sleeping for 3 sec before wait(). If SIGCHLD is set to default handler, then it sleeping for 3 sec, calling wait and returning as expected. What is exactly happening here ??

我无法理解以下程序的输出。我发现在子进程返回后,父进程在wait()之前没有休眠3秒。如果SIGCHLD设置为默认处理程序,则它会休眠3秒,调用wait并按预期返回。到底发生了什么?

# include <unistd.h>
# include <sys/types.h>
# include <stdio.h>
# include <sys/wait.h>
# include <signal.h>

void handler(int sig) {
printf("Iam in handler ...\n");
}

main() {

int status;
pid_t pid;

struct sigaction act;
//act.sa_flags=SA_NOCLDSTOP;
act.sa_handler=handler;
sigaction(SIGCHLD,&act,NULL);

if(!fork()) {
printf("child process id is  %d\n",getpid());
 return 1;
}  

printf("xxx ...\n");
sleep(3);
pid = wait(&status);
printf("process terminated is %d\n",pid);

}

output::

xxx ...
child process id is  2445
Iam in handler ...
process terminated is 2445

2 个解决方案

#1


8  

When the child process dies a SIGCHLD is sent to the parent. In your case it interrupts the sleep and it looks as if the process doesn't sleep.

当子进程终止时,SIGCHLD将发送给父进程。在你的情况下,它会中断睡眠,看起来好像进程没有睡眠。

The gist of the issue: sleep isn't restarted when interrupted by a signal.

问题的要点:当信号中断时,睡眠不会重新启动。

#2


11  

From the man for sleep():

从睡觉的男人():

sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.

sleep()使调用线程处于休眠状态,直到秒数已经过去或者信号到达而未被忽略。

Your child terminating causes a signal to wake you up.

您的孩子终止会导致信号唤醒您。

The return value from sleep():

sleep()的返回值:

Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

如果请求的时间已经过去,则为零;如果呼叫被信号处理程序中断,则为剩余的秒数。

Can be used if you'd like to help you "finish" the sleep.

如果你想帮助你“完成”睡眠,可以使用。

unsigned sleep_time = 3;
...
while((sleep_time = sleep(sleep_time)) > 0) {}
pid = wait(&status);
...

#1


8  

When the child process dies a SIGCHLD is sent to the parent. In your case it interrupts the sleep and it looks as if the process doesn't sleep.

当子进程终止时,SIGCHLD将发送给父进程。在你的情况下,它会中断睡眠,看起来好像进程没有睡眠。

The gist of the issue: sleep isn't restarted when interrupted by a signal.

问题的要点:当信号中断时,睡眠不会重新启动。

#2


11  

From the man for sleep():

从睡觉的男人():

sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.

sleep()使调用线程处于休眠状态,直到秒数已经过去或者信号到达而未被忽略。

Your child terminating causes a signal to wake you up.

您的孩子终止会导致信号唤醒您。

The return value from sleep():

sleep()的返回值:

Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

如果请求的时间已经过去,则为零;如果呼叫被信号处理程序中断,则为剩余的秒数。

Can be used if you'd like to help you "finish" the sleep.

如果你想帮助你“完成”睡眠,可以使用。

unsigned sleep_time = 3;
...
while((sleep_time = sleep(sleep_time)) > 0) {}
pid = wait(&status);
...