关于SIGCHLD和sigaction的疑惑

梁宏 2009-07-22 03:24:57
各位大哥,小弟搞了好久也没整明白,代码如下:
#include "apue.h"
#include<pthread.h>

void show_handler(struct sigaction * act)
{
printf("sigchld catched!\n");
}
main()
{
int i;
pid_t pid;
struct sigaction act,oldact;

act.sa_handler = show_handler;

pid = fork();
if(pid < 0)
printf("fork err!\n");
if(pid == 0)
{
sleep(5);
printf("child process\n");
}
else
sigaction(SIGCHLD,&act,&oldact);
printf("parent process\n");
}



输出:
parent process
[root@localhost threadctl]# child process
parent process

为什么在父进程里面设置了sigaction动作,但却没有执行,并且执行了两次printf("parent process\n");


而:
void show_handler(struct sigaction * act)
{
printf("sigchld catched!\n");
}
main()
{
int i;
pid_t pid;
struct sigaction act,oldact;

act.sa_handler = show_handler;
sigaction(SIGCHLD,&act,&oldact);

pid = fork();
if(pid < 0)
printf("fork err!\n");
if(pid == 0)
{
printf("child process\n");
}
else
printf("parent process\n");
}
确实正常的输出:
child process
sigchld catched!
parent process
...全文
339 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengzhixi 2009-07-23
  • 打赏
  • 举报
回复
mark
梁宏 2009-07-23
  • 打赏
  • 举报
回复
也就是说当我打算捕捉SIGCHLD信号的时候,必须对应后边的一个fork才行,是吧?
而当我在fork之后,再在父进程里面捕捉sigchld信号时,他是不知道去捉哪个信号的。
可以这么理解么
梁宏 2009-07-23
  • 打赏
  • 举报
回复
谢谢各位,小弟受益匪浅
yuyaoit 2009-07-23
  • 打赏
  • 举报
回复
1楼正解!
challenge99 2009-07-22
  • 打赏
  • 举报
回复
父进程先结束,所以sigaction不会被执行

出现两个parent process的原因是,你的else怎不打括号呢!!!!

lihevvv 2009-07-22
  • 打赏
  • 举报
回复
sigaction(SIGCHLD,&act,&oldact);这个在父进程里执行的时候,fork已经执行完毕了,DIGCHLD是捕捉不到的,至于为什么执行了2次parent process,是这样的:第一次是父进程结束执行的,第二次是子进程执行之后执行的。

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧