Reputation: 359
How to run more than 1 command inside open
?
I have a code below. Here, I am running make $i
inside open, but now I want to run more than 1 command here, say make $i; sleep 30; echo abc
. How can I do that?
foreach $i (@testCases) {
my $filehandle;
if ( ! (my $pid = open( $filehandle, "make $i 2>&1 |" ) )) {
die( "Failed to start process: $!" );
}
else {
print "Test started\n";
}
}
Just to add the following is not working properly:
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";
}
Here, I am getting $detailedPs as empty. If things would have run correctly, I would have got something in $detailedPs
Upvotes: 2
Views: 201
Reputation: 385506
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" );
Preferred:
open( my $pipe, "-|", "make $i; sleep 30; echo abc" )
Short for: (non-Windows)
open( my $pipe, "-|", "/bin/sh", "-c", "make $i; sleep 30; echo abc" )
But note that you have a code injection bug. Fixed:
open( my $pipe, "-|", "/bin/sh", "-c", 'make "$1"; sleep 30; echo abc', "dummy", $i )
With IPC::Run:
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" );
But you'd be better off avoiding a shell.
use IPC::Run qw( run );
run(
[ 'make', $i ],
'|', [ 'sleep', '30' ],
'|', [ 'echo', 'abc' ],
'>', \my $stdout
)
or die( "A problem occurred running the command.\n" );
Upvotes: 2