+ -
当前位置:首页 → 问答吧 → parent在sleep的时候受到 child 的sig 为啥就不继续sleep了?

parent在sleep的时候受到 child 的sig 为啥就不继续sleep了?

时间:2010-11-12

来源:互联网

标题不是很清楚。定义了下 SIG{CHLD}的handler
  1. #!/usr/bin/perl -w
  2. use strict;
  3. use POSIX ":sys_wait_h";
  4. our %liveprocess;

  5. $SIG{CHLD}= sub { while( (my $tmp_chl = waitpid(-1,WNOHANG))>0){print "$tmp_chl was delete \n";delete $liveprocess{$tmp_chl};}};

  6. my $pid = fork();
  7. if($pid) {
  8.         print "$pid\n";
  9.         $liveprocess{$pid}="";
  10.         sleep 10;
  11.         if( scalar (keys %liveprocess) >0 ){
  12.                 my @wait_to_kill=keys %liveprocess;
  13.                 kill 9 ,@wait_to_kill;
  14.         }
  15.         print "this is after kill or child finished ,reachit? \n";
  16.         sleep 3;
  17.         print "this is after kill or child finished ,reachit? \n";

  18. }

  19. else {
  20.         print "i am child and iam gonna sleep3 and go to ssh\n";
  21.         sleep 2;
  22.         exit 0 ;
  23. }
复制代码
主要是想在child 超时的时候干掉child 。

child 超时的时候能 kill 掉 。但是 不超时的时候parent马上就退出sleep了
为什么会退出sleep呢?

作者: nuclearxin   发布时间: 2010-11-12

POSIX就是这么设计的。
如果SIGCHLD不能唤醒sleep会存在很多问题。
比如一个server模式里,parent在循环等待childs的结果,它很多时候会sleep来等待,一旦child有退出,它立刻从sleep中苏醒过来进行处理。

不过,parent里可以临时block掉SIGCHLD。

作者: 兰花仙子   发布时间: 2010-11-12

哦。原来与此阿。。。。
其实这样更好。我只等待一个进程。

作者: nuclearxin   发布时间: 2010-11-12