Hi Peter, On 2 Mar 2012 02:48:28 -0000 Peter Scott <pe...@psdt.com> wrote:
> On Sun, 26 Feb 2012 20:30:56 +0100, Manfred Lotz wrote: > > I want to run a shell command with the following constraints: > > > > a. I like to get the return code of the command b. Furthermore I want to > > combine stdout and stderr so that the output comes in a natural sequence > > like in the shell. c. I don't want to capture the output in a variable > > (because the output could be really large and I don't want to wait for > > the first line of output) > > > > I did this: > > > > use IPC::Open3; > > > > sub run_cmd { > > my $cmd = shift @_; > > > > my $pid = open3(undef, *CMD_OUT, *CMD_OUT,$cmd); > > > > while ( <CMD_OUT>) { print "$_"; } > > waitpid($pid,0); > > my $rc = $? >>8; > > return $rc; > > } > > > > > > I tested the code and it I can say it worked fine under fair weather > > conditions. > > > > Question: Is the code ok, or could it be improved, or has it even flaws? > > It doesn't have flaws. You could do it without the module with a piped > open: > > sub run_cmd > { > my $cmd = shift; > > open my $fh, '-|', "$cmd 2>&1" or die "open: $!"; > print while <$fh>; > close $fh; > return $? >> 8; > } Interesting. I did not realise that open '-|' with a single argument will pass this as a small shell program. But it does: <<<< #!/usr/bin/perl use strict; use warnings; sub run_cmd { my $cmd = shift; open my $fh, '-|', "$cmd 2>&1" or die "open: $!"; print while <$fh>; close $fh; return $? >> 8; } run_cmd('ls -l'); >>>> This may cause security problems if you pass an array («open my $fh, '-|', @cmd or die …») because if it contains only one element, then you're risking code/markup injection. And open does not appear to support system()'s or exec()'s «system { $args[0] } @args» paradigm. When I asked people on #p5p (the Perl 5 Porters channel) about it, they told me that open sucks for that and that one should use https://metacpan.org/release/IPC-Run or https://metacpan.org/release/IPC-System-Simple (depending on what you want to do) instead. Regards, Shlomi Fish -- ----------------------------------------------------------------- Shlomi Fish http://www.shlomifish.org/ Interview with Ben Collins-Sussman - http://shlom.in/sussman Confucius says: “XSLT made me realise humanity was hopeless.”. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/