[英]Perl: How to run more than 1 command inside open while opening a filehandle into commands
如何在open
中運行超過 1 個命令?
我在下面有一個代碼。 在這里,我在 open 中運行make $i
,但現在我想在這里運行多個命令,比如make $i; sleep 30; echo abc
make $i; sleep 30; echo abc
make $i; sleep 30; echo abc
。 我怎樣才能做到這一點?
foreach $i (@testCases) {
my $filehandle;
if ( ! (my $pid = open( $filehandle, "make $i 2>&1 |" ) )) {
die( "Failed to start process: $!" );
}
else {
print "Test started\n";
}
}
僅添加以下內容無法正常工作:
if (!($pid = open( my $pipe, "make $i; sleep 30; echo abc |" ))) " {
print "Problem in openeing a filehandle\n";
} else {
print "$pid is pid\n";
my $detailedPs=`tasklist | grep "$pid"`;
chomp ($detailedPs);
print "$detailedPs is detailedPs\n";
}
在這里,我得到 $detailedPs 為空。 如果事情能正常運行,我會在 $detailedPs 中得到一些東西
open( my $pipe, "make $i; sleep 30; echo abc |" )
or die( "Can't launch shell: $!\n" );
my $stdout = join "", <$pipe>; # Or whatever.
close( $pipe )
or die( "A problem occurred running the command.\n" );
首選:
open( my $pipe, "-|", "make $i; sleep 30; echo abc" )
縮寫:(非 Windows)
open( my $pipe, "-|", "/bin/sh", "-c", "make $i; sleep 30; echo abc" )
但請注意,您有一個代碼注入錯誤。 固定的:
open( my $pipe, "-|", "/bin/sh", "-c", 'make "$1"; sleep 30; echo abc', "dummy", $i )
使用 IPC::運行:
use IPC::Run qw( run );
run(
[ "/bin/sh", "-c", 'make "$1"; sleep 30; echo abc', "dummy", $i ],
'>', \my $stdout # Or whatever.
)
or die( "A problem occurred running the command.\n" );
但是你最好避免使用 shell。
use IPC::Run qw( run );
run(
[ 'make', $i ],
'|', [ 'sleep', '30' ],
'|', [ 'echo', 'abc' ],
'>', \my $stdout
)
or die( "A problem occurred running the command.\n" );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.