了解SIGCHLD当子进程结束 [英] Understanding SIGCHLD when the child process terminates

查看:216
本文介绍了了解SIGCHLD当子进程结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能够理解以下程序的输出。我观察到,子进程返回后,父进程不睡觉,持续3秒的等待()之前。如果SIGCHLD被设置为默认的处理器,那么它睡了3秒,调用wait和返回预期。究竟是什么在这里发生的?

 #包括LT&;&unistd.h中GT;
#包括LT&; SYS / types.h中>
#包括LT&;&stdio.h中GT;
#包括LT&; SYS / wait.h>
#包括LT&;&signal.h中GT;无效的处理程序(INT SIG){
的printf(荫中处理... \\ n);
}主(){INT状态;
将为pid_t PID;结构sigaction的行为;
//act.sa_flags=SA_NOCLDSTOP;
act.sa_handler =处理程序;
的sigaction(SIGCHLD,&安培;行为,NULL);如果(!叉()){
的printf(子进程ID为%d \\ n,GETPID());
 返回1;
}的printf(XXX ... \\ n);
睡眠(3);
PID =等待(安培;状态);
的printf(终止进程为%d \\ n,PID);}输出::XXX ...
子进程ID是2445
在荫...处理器
终止的进程是2445


解决方案

在子进程死一个 SIGCHLD 发送给家长。在你的情况下,它会中断睡眠,它看起来仿佛过程不睡觉。

问题的要点:睡眠时,信号中断是没有重新启动

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 ??

# 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

解决方案

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.

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

这篇关于了解SIGCHLD当子进程结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆