Perl中system和反引号··的使用区别的

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值