+ -
当前位置:首页 → 问答吧 → sleep在多进程中的问题

sleep在多进程中的问题

时间:2011-04-03

来源:互联网

本帖最后由 reallyfly_1 于 2011-04-03 19:23 编辑

本想测试一下FORK的使用,写了如下代码,意思是:

1.不断的从父进程创建5个子进程
2.父进程创建完子进程后睡眠3秒
3.睡眠后挂起所有的子进程


但是里面的sleep运行时间总是不对。
sleep的返回值是真正‘睡眠’的时间,但是如下代码在我的机器上返回的总是1。

本人新手,求帮助

#!/usr/bin/perl -w
use strict;
use POSIX 'WNOHANG';
$| = 1;
print "main PID=$$\n";


$SIG{CHLD} = sub{
        while((my $kid = waitpid(-1, WNOHANG)) > 0)
        {
                print "reaped child...\n";
        }
};


my $child_1 = 1;

foreach my $i (1..5)
{
        if($child_1 > 0)
        {
                $child_1 = fork();
        }

        if($child_1 > 0)
        {
                print "this is father, PID=$$\n";
        }elsif($child_1 == 0){
                $child_1 = -1;
                sleep($i);
                print "this is child, PID=$$\n";
        }
}


if($child_1 > 0)
{
        setpgrp(0,0);
        local $SIG{HUP} = 'IGNORE';
        print "I am $$, I will kill all, after sleep\n";
        my $time = sleep(3);
        print "sleep over $time sec, begin\n";
        kill('HUP', -$$);
}

作者: reallyfly_1   发布时间: 2011-04-03

本帖最后由 027xiatian 于 2011-04-05 10:13 编辑
  1.        if($child_1 > 0)
  2.         {
  3.                 print "this is father, PID=$$\n";
  4.         }elslif ($child_1 == 0){
  5.                 $child_1 = -1;
  6.                 sleep($i);
  7.                 print "this is child, PID=$$\n";
  8.         }
复制代码
elsif的代码执行不到吧(不知道如何标记成红色)

作者: 027xiatian   发布时间: 2011-04-05