在Perl中用system、exec、readpipe函數來執行系統命令html
轉自:http://cn.waterlin.org/less
在Perl中,能夠用system、exec、readpipe這三個命令來調用其餘腳本、系統命令等。這三個命令的主要區別就是返回值。函數
1) 對於system這個函數來講,它會返回執行後的狀態,好比說post
@args = (「command」, 「arg1″, 「arg2″);
system(@args) == 0
or die 「system @args failed: $?」spa
固然,你也能夠用相似於下面的語句來檢查出錯的緣由:日誌
if ($? == -1) {
print 「failed to execute: $!\n」;
}
elsif ($? & 127) {
printf 「child died with signal %d, %s coredump\n」,
($? & 127), ($? & 128) ? ‘with’ : ‘without’;
}
else {
printf 「child exited with value %d\n」, $? >> 8;
}htm
2) 而對於exec這個函數來講,僅僅是執行一個系統的命令,通常狀況下並無返回值。exec只有在系統沒有你要執行的命令的狀況下,纔會返回false值。blog
exec (‘foo’) or print STDERR 「couldn’t exec foo: $!」;
{ exec (‘foo’) }; print STDERR 「couldn’t exec foo: $!」;進程
3) 當咱們須要保存系統命令運行的結果,以便分析並做進一步的處理時,就要用到readpipe這個函數了。例如:ip
@result = readpipe( 「ls -l /tmp」 );
print 「@result」;
會產生以下的結果:
drwxr-xr-x 2 root root 4096 Mar 19 11:55 testdir
固然,你也能夠把生成的結果放到一個文件裏,以便寫工做日誌呀、發佈報告呀。
$inject_command = 「./ConfigChecker.bat F:/nic/3502/ARRAY-4AD2E0573/etc 「.$device_name;
chdir 「F:/TestTools/bin/」;
@temp_result = readpipe($inject_command);
open(result_file,」>result.txt」);
print result_file @temp_result;
close(result_file);
這樣,你就把系統運行的結果扔到了系統命令所在目錄下的result.txt文件裏了。
完!