Skip to content

Instantly share code, notes, and snippets.

@alh13
Created June 22, 2012 02:26
Show Gist options
  • Save alh13/2969851 to your computer and use it in GitHub Desktop.
Save alh13/2969851 to your computer and use it in GitHub Desktop.
extra-careful subprocesses in Perl
# Here's an idiom to spawn a subprocess and capture its output, without fear of
# being attacked by shell metachars
# (Perl's backtick operator spawns a shell)
sub safeticks {
my $retval = '';
my $line;
my $pid;
die "Can't fork: $!" unless defined($pid = open(KID, "-|"));
if ($pid) { # parent
while (defined($line = <KID>)) {
$retval .= $line;
}
close KID;
}
else {
exec @_;
}
return $retval;
}
# Here's a remarkably similar technique from git 1.7.7 source. It is better
# in some ways and in some ways worse. I should probably combine them.
sub safe_pipe_capture {
my @output;
if (my $pid = open my $child, '-|') {
@output = (<$child>);
close $child or die join(' ',@_).": $! $?";
} else {
exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
}
return wantarray ? @output : join('',@output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment