测试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($pid, 0);
} 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($pid, 0);
}
}
}
}
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);
}
运行界面: