#!/usr/bin/perl
use warnings;
use IPC::Open3;
use IO::Select;
use POSIX ":sys_wait_h";
use Symbol;
sub run
{
my ($WRITE, $READ, $ERROR);
$ERROR=gensym();
my $command="not_a_command";
my $error="";
my $output="";
eval { $pid=open3($WRITE, $READ, $ERROR, "$command"); };
if (!$pid) {
# if we get here, the fork succeeded, but the exec (likely) failed...
my $err = $@ ? $@ : "unknown error";
# exit child in any case
die "Error: Could not execute $command: $err";
} else {
close($WRITE);
my $selector=IO::Select->new();
$selector->add($READ, $ERROR);
while(@ready=$selector->can_read)
{
foreach (@ready)
{
if(fileno($_)==fileno($READ))
{
$bytes=sysread($READ, $text, 1024);
if($bytes==0) { $selector->remove($_); }
else { $output.=$text; }
}
elsif(fileno($_)==fileno($ERROR))
{
$bytes=sysread($ERROR, $text, 1024);
if($bytes==0) { $selector->remove($_); }
else { $error.=$text; }
}
}
}
waitpid($pid, 0);
}
return($output, $error);
}
my ($output, $error);
($output, $error)=run();
print "$output, $error\n";
####
$ ./test_eval.pl
, Error: Could not execute not_a_command: open3: exec of not_a_command failed at ./test_eval.pl line 22
####
...
if (!$pid) {
# if we get here, the fork succeeded, but the exec (likely) failed...
my $err = $@ ? $@ : "unknown error";
# return error, and exit child
print STDERR "Error: Could not execute $command: $err";
POSIX::_exit($!);
}
...