Guest User

Untitled

a guest
Oct 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. # Here's an idiom to spawn a subprocess and capture its output, without fear of
  2. # being attacked by shell metachars
  3. # (Perl's backtick operator spawns a shell)
  4. sub safeticks {
  5. my $retval = '';
  6. my $line;
  7. my $pid;
  8.  
  9. die "Can't fork: $!" unless defined($pid = open(KID, "-|"));
  10. if ($pid) { # parent
  11. while (defined($line = <KID>)) {
  12. $retval .= $line;
  13. }
  14. close KID;
  15. }
  16. else {
  17. exec @_;
  18. }
  19. return $retval;
  20. }
  21.  
  22. # Here's a remarkably similar technique from git 1.7.7 source. It is better
  23. # in some ways and in some ways worse. I should probably combine them.
  24. sub safe_pipe_capture {
  25.  
  26. my @output;
  27.  
  28. if (my $pid = open my $child, '-|') {
  29. @output = (<$child>);
  30. close $child or die join(' ',@_).": $! $?";
  31. } else {
  32. exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
  33. }
  34. return wantarray ? @output : join('',@output);
  35. }
Add Comment
Please, Sign In to add comment