perl调用子进程的最简单的方式是用system。
1. 返回值问题
1> $out = system "date";
print "out: $out\n";
output:
Mon Jul 24 11:25:50 EDT 2017
out: 0 (执行成功的时候,system返回的值是0,如果想要将命令的运行结果放入到变量$out中,要用`date`)
my $out = `date`;
print "$out\n";
output:
test]# perl test.pl
Fri Feb 2 09:13:00 EST 2018
2> $out = system "datea"; (错误的命令)
print "out: $out\n";
output:
out: -1(执行成功的时候,system返回的值是非零)
system函数的返回值低8位存Unix Signal,高位存命令执行的返回值,因此,如果需要判断shell命令是否执行成功,必须判断返回的值是否为0.
2. 后台运行问题
有时想要在后台运行shell命令,只要用nohup shell命令 &即可。而在perl中应该使用system调用这条命令,而不是反引号。
实验如下:
1> 使用反引号:
my $cmd = "nohup ping www.baidu.com -c 10";
my $out = `$cmd`;
print "$out\n";
Output:
test]# perl test.pl
nohup: ignoring input and redirecting stderr to stdout (会直至hang在这里等到ping命令结束后打印出结果才会退出)
PING www.a.shifen.com (61.135.169.125) 56(84) bytes of data.
64 bytes from 61.135.169.125: icmp_seq=1 ttl=55 time=24.1 ms
64 bytes from 61.135.169.125: icmp_seq=2 ttl=55 time=23.9 ms
64 bytes from 61.135.169.125: icmp_seq=3 ttl=55 time=24.2 ms
64 bytes from 61.135.169.125: icmp_seq=4 ttl=55 time=24.0 ms
64 bytes from 61.135.169.125: icmp_seq=5 ttl=55 time=24.0 ms
64 bytes from 61.135.169.125: icmp_seq=6 ttl=55 time=24.4 ms
64 bytes from 61.135.169.125: icmp_seq=7 ttl=55 time=24.0 ms
64 bytes from 61.135.169.125: icmp_seq=8 ttl=55 time=24.1 ms
64 bytes from 61.135.169.125: icmp_seq=9 ttl=55 time=24.2 ms
64 bytes from 61.135.169.125: icmp_seq=10 ttl=55 time=24.3 ms
--- www.a.shifen.com ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 11684ms
rtt min/avg/max/mdev = 23.986/24.183/24.488/0.229 ms
2> system
my $cmd = "nohup ping www.baidu.com -c 1000 &";
my $out = system $cmd;
print "$out\n";
Output:
test]# perl test.pl
0
[root@TB-Arlene-PC2 test]# nohup: appending output to `nohup.out'