勤能补拙,厚积薄发

合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下
随笔 - 19, 文章 - 0, 评论 - 3, 引用 - 0
数据加载中……

[Perl]通过客户端请求服务端运行指定程序,支持多进程

测试HTTP服务器性能时候用的,通过客户端请求服务端运行指定程序,支持多进程,可用参数控制
服务端代码:
#!/usr/bin/perl -w
use strict;
use IO::Socket;
my $port = 9800;
my $filename;
my $proc_n;
my $pid;
my @pidarr;
my $command;
my @fullline;
my $sock = new IO::Socket::INET( 
        LocalPort => $port,
        Proto => 'tcp',
        Listen => 5,
        Reuse => 1);
die "Could not bind: $!" unless $sock;
while (my $c_sock = $sock->accept()) {
    while (defined (my $buf = <$c_sock>)) {
        chomp($buf);
#        print "$buf\n";
        @fullline = split /\t/, $buf;
        $command = $fullline[0];
        $proc_n = $fullline[1];
        $filename = $fullline[2];
        if ($proc_n == 1) {
            defined ($pid = fork) or die "Can't fork: $!";
            unless ($pid) {
                do_work($command$filename."\.txt");
                exit 0;
            }
            waitpid($pid0);
        } else {
            my $i;
            for ($i = 1$i <= $proc_n$i += 1) {
                defined ($pid = fork) or die "Can't fork: $!";
                unless ($pid) {
                    do_work($command$filename."$i\.txt");
                    exit 0;
                }
                push(@pidarr$pid);
            }
            foreach $pid (@pidarr) {
                waitpid($pid0);
            }
        }
    }
}
close ($sock);

sub do_work {
    system "/bin/bash""-c""$_[0] >> $_[1]";
}

客户端代码:
#!/usr/bin/perl -w
use strict;
use IO::Socket;
if (@ARGV < 2) {
    print "wrong parameter, ./*.pl [command] [proc_n] [filename] [ip n]\n";
    print "command:  the command you want the peer pc to run.\n";
    print "proc_n:   the num of process the peer pc would run the command.\n";
    print "filename: the filename of file to save the output in peer pc.\n";
    exit 0;
}
my $port = 9800;
my $command = $ARGV[0];
my $proc_n = $ARGV[1];
my $filename = $ARGV[2];
my @iparr;
for (my $i = 3$i < @ARGV$i++) {
    push(@iparr$ARGV[$i]);
}
my @pidarr;
my $pid;
my $ipaddr;
foreach $ipaddr (@iparr) {
    defined ($pid = fork) or die "Can't fork: $!";
    push(@pidarr$pid);
    unless ($pid) {
        connect_work($ipaddr$port, (join "\t"$command$proc_n$filename));
        exit 0;
    }
}
foreach $pid (@pidarr) {
    waitpid($pid,0);
}

sub connect_work {
    my $sock = new IO::Socket::INET(PeerAddr => $_[0], 
            PeerPort => $_[1],
            Proto => 'tcp');
    if ($sock) {
        print "connect $_[0]:$_[1] successful!\n";
    } else {
        print "can't connect to $_[0]:$_[1], client exit: $!\n";
        exit 1;
    }
    print $sock "$_[2]\n";
    $sock->flush();
    close ($sock);
}

运行界面:


posted on 2012-08-10 11:06 lee007 阅读(355) 评论(0)  编辑 收藏 引用 所属分类: Perl/Python


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理