处理多个信号时产生的问题

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

void handler( int sig )
{
    pid_t pid;

    if( (pid=waitpid(-1, NULL, 0)) < 0 )
              perror( "waitpid error" );
     
      printf( "handler reaped child %d\n", (int)pid );
      sleep( 2 );

      return;
}

int main( int argc, char **argv )
{
      int i,n;
      char buf[20];

      if( signal(SIGCHLD, handler) == SIG_ERR )
              perror( "signal error" );
      for( i = 0; i < 3; i++ )
      {
              if( fork() == 0 )
              {
                      printf( "hello from child %d\n", (int)getpid() );
                      sleep( 1 );
                      exit( 0 );
              }
      }
      if( (n=read(STDIN_FILENO, buf, sizeof(buf))) < 0 )
              perror( "read" );
      printf( "parent processing input\n" );
      while( 1 );

      exit( 0 );
}

程序输出:
hello from child 3556
hello from child 3557
hello from child 3558
handler reaped child 3556
handler reaped child 3557
可见进程3558没有被回收。
原因:父进程创建了3个子进程,并等待其中子进程的终止信号。
父进程接收捕获了第一个SIGCHLD信号(进程3556的终止信号)。当处理程序还在处理第一个信号时,第二个SIGCHLD信号(进程3557的终止信号)就传送添加到了待处理信号集了,并等待前一个SIGCHLD处理程序的结束(也就是被前一个阻塞)。很快,当处理程序还在处理第一个信号时,第三个信号(进程3558终止信号)来了,由于 任意类型至多只有一个待处理信号,所以信号3被丢弃。当第一个信号的处理程序返回后,内核执行第二个信号的处理程序。这样,第三个信号久丢失了。
修正方法:
改变信号处理程序:
void handler( int sig )
{
    pid_t pid;

    while( (pid=waitpid(-1, NULL, 0)) > 0 )
              printf( "handler reaped child %d\n", (int)pid );
          //  perror( "waitpid error" );
     
     
      sleep( 2 );

      return;
}

输出:
hello from child 3551
hello from child 3552
hello from child 3553
handler reaped child 3551
handler reaped child 3552
handler reaped child 3553
改动原理:
存在一个待处理信号只是暗示自进程最后一次收到一个信号以来,至少已经有一个这种类型的信号被发送了。所以应该在每次信号处理函数被调用时,回收尽可能多的僵死进程。这样就不会发生上述情况。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值