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'

發佈了66 篇原創文章 · 獲贊 34 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章