[英]Understanding SIGCHLD when the child process terminates
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().
我观察到在子进程返回后,父进程在wait()之前没有休眠3秒。 If SIGCHLD is set to default handler, then it sleeping for 3 sec, calling wait and returning as expected.
如果SIGCHLD设置为默认处理程序,则它会休眠3秒,调用wait并按预期返回。 What is exactly happening here ??
到底发生了什么?
# 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
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);
...
When the child process dies a SIGCHLD
is sent to the parent. 当子进程
SIGCHLD
将发送给父进程。 In your case it interrupts the sleep
and it looks as if the process doesn't sleep. 在你的情况下,它会中断
sleep
,看起来好像进程没有睡眠。
The gist of the issue: sleep
isn't restarted when interrupted by a signal. 问题的要点:当信号中断时,
sleep
不会重新启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.