2007年7月10日星期二

Multi-processes

使用 fork() 时需要注意的问题:

1. 记录 fork 出的子进程 id,收割进程时验证
2. parent process 和 child process 有各自独立的进程空间
3. 使用 exit 结束 child process
4. 已没有需要回收的 child process 时 wait() 返回 -1

下面是测试局域网中机器联网状态的程序(使用 icmp 扫描,可接收到反馈则认为已联网)。

#! /usr/bin/perl
use warnings;
use strict;

my $host_prefix = '192.168.0.';
my @hosts;
for ( 80 .. 200) {
    my $host = $host_prefix . " $_";
    push(@hosts, $host);
}

my $number_of_process = 20;
my %counter_process;

use Net::Ping;
my $p = Net::Ping->new('icmp', 2);
for my $h (@hosts) {
    if (keys(%counter_process) > $number_of_process)
    { reap_process(\%counter_process) }

    if (my $process = fork)
    { $counter_process{$process} = $h }
    elsif (defined($process)) {
        if ($p->ping($h)) { print "$h is alive\n" }
        else { print "$h is not alive \n" }

        exit 0;
    } else { die "Something wrong at this $! " }
}
$p->close;

1 while (reap_process(\%counter_process ));

# functions definition -----------------
sub reap_process {
    my $process_hash = $_[0];
    my $pid = wait;
    return 0 if ( $pid == -1);

    delete($process_hash->{$pid}) or warn(" Cannot see $pid\n");

    1; # if reap a child
}

没有评论: