File Coverage

blib/lib/Proc/SafeExec.pm
Criterion Covered Total %
statement 152 193 78.7
branch 85 158 53.8
condition 9 24 37.5
subroutine 16 19 84.2
pod 3 10 30.0
total 265 404 65.5


line stmt bran cond sub pod time code
1             package Proc::SafeExec;
2              
3 6     6   61482 use 5.006;
  6         18  
  6         222  
4 6     6   36 use strict;
  6         6  
  6         900  
5 6     6   30 use warnings;
  6         1152  
  6         750  
6              
7             our $VERSION = "1.5";
8              
9             =pod
10              
11             =head1 NAME
12              
13             Proc::SafeExec - Convenient utility for executing external commands in various ways.
14              
15             =head1 SYNOPSIS
16              
17             use Proc::SafeExec;
18             $SIG{"CHLD"} = "DEFAULT"; # Not IGNORE, so we can collect exit status.
19             my $command = Proc::SafeExec->new({
20             # Choose just one of these.
21             "exec" => ["ls", "-l", "myfile"], # exec() after forking.
22             "fork" => 1, # Return undef in the child after forking.
23              
24             # Specify whether to capture each. Specify a file handle ref to dup an existing
25             # one. Specify "new" to create a new file handle, "default" or undef to keep
26             # the parent's descriptor, or "close" to close it.
27             "stdin" => \*INPUT_PIPE,
28             "stdout" => \*OUTPUT_PIPE,
29             "stderr" => "new",
30              
31             # Miscellaneous options.
32             "child_callback" => \&fref, # Specify a function to call in the child after fork(), for example, to drop privileges.
33             "debug" => 1, # Emit some information via warnings, such as the command to execute.
34             "no_autowait" => 1, # Don't automatically call $command->wait() when $command is destroyed.
35             "real_arg0" => "/bin/ls", # Specify the actual file to execute.
36             "untaint_args" => 1, # Untaint the arguments before exec'ing.
37             });
38             printf "Child's PID is %s\n", $command->child_pid() if $command->child_pid();
39              
40             The wait method waits for the child to exit or checks whether it already
41             exited:
42              
43             $command->wait({
44             # Optional hash of options.
45             "no_close" => 1, # Don't close "new" file handles.
46             "nonblock" => 1, # Don't wait if the child hasn't exited (implies no_close).
47             });
48              
49             To communicate with the child:
50              
51             # Perl doesn't understand <$command->stdout()>.
52             my $command_stdout = $command->stdout();
53             my $command_stderr = $command->stderr();
54              
55             $line = <$command_stdout>;
56             $line = <$command_stderr>;
57             print {$command->stdin()} "mumble\n";
58              
59             To check whether the child exited yet:
60              
61             print "Exit status: ", $command->exit_status(), "\n" if $command->wait({"nonblock" => 1});
62              
63             To wait until it exits:
64              
65             $command->wait();
66             print "Exit status: ", $command->exit_status(), "\n";
67              
68             A convenient quick tool for an alternative to $output = `@exec`:
69              
70             ($output, $?) = Proc::SafeExec::backtick(@exec);
71              
72             =head1 DESCRIPTION
73              
74             Proc::SafeExec provides an easy, safe way to execute external programs. It
75             replaces all of Perl's questionable ways of accomodating this, including
76             system(), open() with a pipe, exec(), back-ticks, etc. This module will never
77             automatically invoke /bin/sh. This module is easy enough to use that /bin/sh
78             should be unnecessary, even for complex pipelines.
79              
80             For all errors, this module dies setting $@.
81              
82             Errors from exec() in the child are reported gracefully to the parent. This
83             means that if anything fails in the child, the error is reported through $@
84             with die just like any other error. This also reports $@ if child_callback
85             dies when it is called between fork() and exec(). This is accomplished by
86             passing $@ through an extra pipe that's closed when exec succeeds. Note: A
87             side-effect of this is $@ is stringified if it isn't a string.
88              
89             =head1 CAVEATS
90              
91             When using an existing file handle by passing a reference for stdin, stdout, or
92             stderr, new() closes the previously open file descriptor. This is to make sure,
93             for example, that when setting up a pipeline the child process notices EOF on
94             its stdin. If you need this file handle to stay open, dup it first. For
95             example:
96              
97             open my $tmp_fh, "<&", $original_fh or die "dup: $!";
98             my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => $tmp_fh});
99             # $tmp_fh is now closed.
100              
101             By default, $command->wait() closes any new pipes opened in the constructor.
102             This is to prevent a deadlock where the child is waiting to read or write and
103             the parent is waiting for the child to exit. Pass no_close to $command->wait()
104             to prevent this (see above). Also, by default the destructor calls
105             $command->wait() if child hasn't finished. This is to prevent zombie processes
106             from inadvertently accumulating. To prevent this, pass no_autowait to the
107             constructor. The easiest way to wait for the child is to call the wait method,
108             but if you need more control, set no_autowait, then call child_pid to get the
109             PID and do the work yourself.
110              
111             This will emit a warning if the child exits with a non-zero status, and the
112             caller didn't inspect the exit status, and the caller didn't specify
113             no_autowait (which may imply the exit status might not be meaningful). It's bad
114             practice not to inspect the exit status, and it's easy enough to quiet this
115             warning if you really don't want it by calling $command->exit_status() and
116             discarding the result.
117              
118             =head1 EXAMPLES
119              
120             It's easy to execute several programs to form a pipeline. For the first
121             program, specify "new" for stdout. Then execute the second one, and specify
122             stdout from the first one for the stdin of the second one. For example, here's
123             how to write the equivalent of system("ls | sort > output.txt"):
124              
125             open my $output_fh, ">", "output.txt" or die "output.txt: $!\n";
126             my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => "new"});
127             my $sort = new Proc::SafeExec({"exec" => ["sort"], "stdin" => $ls->stdout(), "stdout" => $output_fh});
128             $ls->wait();
129             $sort->wait();
130             printf "ls exited with status %i\n", ($ls->exit_status() >> 8);
131             printf "sort exited with status %i\n", ($sort->exit_status() >> 8);
132              
133             =head1 INSTALLATION
134              
135             This module has no dependencies besides Perl itself. Follow your favorite
136             standard installation procedure.
137              
138             To test the module, run the following command line:
139              
140             $ perl -e 'use Proc::SafeExec; print Proc::SafeExec::test();'
141              
142             =head1 VERSION AND HISTORY
143              
144             =over
145              
146             =item * Version 1.5, released 2013-06-14. Fixed bug: Open /dev/null for STDIN
147             STDOUT STDERR instead of leaving closed when "close" is specified. Also,
148             recommend in doc to set $SIG{"CHLD"} = "DEFAULT".
149              
150             =item * Version 1.4, released 2008-05-30. Added Proc::SafeExec::backtick()
151             function for convenience. Fixed a couple minor bugs in error handling (not
152             security related). Invalidate $? after reading it so callers must fetch the
153             exit status through $self->exit_status().
154              
155             =item * Version 1.3, released 2008-03-31. Added Proc::SafeExec::Queue. Emit a
156             warning when non-zero exit status, and the caller didn't inspect the exit
157             status, and the caller didn't specify no_autowait (which may imply the exit
158             status might not be meaningful).
159              
160             =item * Version 1.2, released 2008-01-22. Tweaked test() to handle temp files
161             correctly, addressing https://rt.cpan.org/Ticket/Display.html?id=32458 .
162              
163             =item * Version 1.1, released 2008-01-09. Fixed obvious bug.
164              
165             =item * Version 1.0, released 2007-05-23.
166              
167             =back
168              
169             =head1 SEE ALSO
170              
171             The source repository is at git://git.devpit.org/Proc-SafeExec/
172              
173             See also Proc::SafeExec::Queue.
174              
175             =head1 MAINTAINER
176              
177             Leif Pedersen, Ebilbo@hobbiton.orgE
178              
179             =head1 COPYRIGHT AND LICENSE
180              
181             This may be distributed under the terms below (BSD'ish) or under the GPL.
182            
183             Copyright (c) 2007
184             All Rights Reserved
185             Meridian Environmental Technology, Inc.
186             4324 University Avenue, Grand Forks, ND 58203
187             http://meridian-enviro.com
188            
189             Redistribution and use in source and binary forms, with or without
190             modification, are permitted provided that the following conditions are
191             met:
192            
193             1. Redistributions of source code must retain the above copyright
194             notice, this list of conditions and the following disclaimer.
195            
196             2. Redistributions in binary form must reproduce the above copyright
197             notice, this list of conditions and the following disclaimer in the
198             documentation and/or other materials provided with the
199             distribution.
200            
201             THIS SOFTWARE IS PROVIDED BY AUTHORS AND CONTRIBUTORS "AS IS" AND ANY
202             EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
203             IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
204             PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE
205             LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
206             CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
207             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
208             BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
209             WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
210             OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
211             ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
212              
213             =cut
214              
215 6     6   36 use Fcntl "F_GETFL", "F_SETFL", "FD_CLOEXEC";
  6         6  
  6         306  
216 6     6   30 use File::Spec;
  6         12  
  6         102  
217 6     6   12708 use File::Temp;
  6         275490  
  6         492  
218 6     6   9894 use POSIX "WNOHANG";
  6         120804  
  6         42  
219              
220             # Remember, any place new() dies or does not return $self triggers DESTROY
221             # immediately.
222             sub new {
223 20     20 0 92 my ($package, $options) = @_;
224 20   33     324 my $self = bless {}, (ref($package) or $package);
225              
226             # Be sure we don't gain extra references to any file handles or clobber
227             # anything the caller needs. For example, if the caller holds a reference to
228             # $options and we add a file handle reference to it, the file handle will not
229             # be destroyed when we expect.
230 20         103 $options = {%$options};
231              
232             # Usage checks; set defaults.
233 20         744 $self->{"debug"} = $options->{"debug"};
234 20 100       113 $options->{"stdin"} = "default" unless defined $options->{"stdin"};
235 20 100       76 $options->{"stdout"} = "default" unless defined $options->{"stdout"};
236 20 50       100 $options->{"stderr"} = "default" unless defined $options->{"stderr"};
237 20 50 33     152 die "No action specified for child process\n" unless $options->{"exec"} or $options->{"fork"};
238 20 50 33     243 die "More than one action specified for child process\n" if $options->{"exec"} and $options->{"fork"};
239 20 50 33     98 warn "Executing: @{$options->{'exec'}}\n" if $self->{"debug"} and $options->{"exec"};
  0         0  
240 20 50       65 if($options->{"exec"}) {
241 20         79 my $count = -1;
242 20         52 while(++$count < @{$options->{"exec"}}) {
  40         148  
243 20 50       67 die "Argument $count to exec is undef\n" unless defined $options->{"exec"}[$count];
244             }
245             }
246              
247             # Regarding file handles, $self holds the side that the parent will see and
248             # $options holds the side that the child will see. Remember, if we're passed a
249             # file handle reference, the parent closes it after passing it to the child.
250              
251             # Prepare file descriptors.
252 20 100       1125 if(ref $options->{"stdin"}) {
    100          
    50          
    50          
253             # Empty
254             } elsif($options->{"stdin"} eq "new") {
255 4         16 $self->{"stdin"} = undef;
256 4         12 $options->{"stdin"} = undef;
257             # Careful of the order. It's pipe README, WRITEME.
258 4 50       132 pipe $options->{"stdin"}, $self->{"stdin"} or die "pipe: $!\n";
259 4         20 set_cloexec($self->{"stdin"});
260 4         16 set_cloexec($options->{"stdin"});
261             } elsif($options->{"stdin"} eq "close") {
262             # Empty
263             } elsif($options->{"stdin"} eq "default") {
264             # Empty
265             } else {
266 0         0 die "Unknown option for stdin: $options->{'stdin'}\n";
267             }
268 20 100       156 if(ref $options->{"stdout"}) {
    100          
    50          
    50          
269             # Empty
270             } elsif($options->{"stdout"} eq "new") {
271 6         18 $self->{"stdout"} = undef;
272 6         12 $options->{"stdout"} = undef;
273             # Careful of the order. It's pipe README, WRITEME.
274 6 50       198 pipe $self->{"stdout"}, $options->{"stdout"} or die "pipe: $!\n";
275 6         72 set_cloexec($self->{"stdout"});
276 6         18 set_cloexec($options->{"stdout"});
277             } elsif($options->{"stdout"} eq "close") {
278             # Empty
279             } elsif($options->{"stdout"} eq "default") {
280             # Empty
281             } else {
282 0         0 die "Unknown option for stdout: $options->{'stdout'}\n";
283             }
284 20 50       190 if(ref $options->{"stderr"}) {
    50          
    50          
    50          
285             # Empty
286             } elsif($options->{"stderr"} eq "new") {
287 0         0 $self->{"stderr"} = undef;
288 0         0 $options->{"stderr"} = undef;
289             # Careful of the order. It's pipe README, WRITEME.
290 0 0       0 pipe $self->{"stderr"}, $options->{"stderr"} or die "pipe: $!\n";
291 0         0 set_cloexec($self->{"stderr"});
292 0         0 set_cloexec($options->{"stderr"});
293             } elsif($options->{"stderr"} eq "close") {
294             # Empty
295             } elsif($options->{"stderr"} eq "default") {
296             # Empty
297             } else {
298 0         0 die "Unknown option for stderr: $options->{'stderr'}\n";
299             }
300              
301             # Set the close-on-exec flag for both ends in both processes since the child
302             # indicates the success of exec() by closing the pipe.
303 20 50       790 pipe my $error_pipe_r, my $error_pipe_w or die "pipe: $!\n";
304 20         104 set_cloexec($error_pipe_r);
305 20         54 set_cloexec($error_pipe_w);
306 20         322 select((select($error_pipe_w), $| = 1)[0]); # Set autoflushing for writing.
307              
308 20         38578 $self->{"child_pid"} = fork();
309 20 50       745 die "fork: $!\n" unless defined $self->{"child_pid"};
310              
311 20 100       637 if($self->{"child_pid"}) {
312             # Parent
313 15         71 $self->{"need_wait"} = 1;
314 15         238 $error_pipe_w = undef;
315              
316 15 100       1196 close $options->{"stdin"} if ref $options->{"stdin"};
317 15 100       481 close $options->{"stdout"} if ref $options->{"stdout"};
318 15 50       114 close $options->{"stderr"} if ref $options->{"stderr"};
319              
320             # EOF indicates no error. This blocks until exec() succeeds or fails because in
321             # the child, $error_pipe_w automatically closes on exec or exit.
322 15 100       6839396 if(defined (my $err = <$error_pipe_r>)) {
323 1         17 chomp $err;
324 1         71 die "$err\n";
325             }
326              
327             # Don't set this until just before returning because if the constructor dies,
328             # the child must be cleaned.
329 14         626 $self->{"no_autowait"} = $options->{"no_autowait"};
330              
331 14         1363 return $self;
332             }
333              
334             # Child
335              
336             # Trap dies and force the child to exit instead because the caller isn't
337             # expecting both to return.
338 5         384 eval {
339 5         145 $error_pipe_r = undef;
340              
341             # This can matter if the child isn't going to call exec(), since the object is
342             # then destroyed when the child returns.
343 5         533 $self->{"no_autowait"} = 1;
344              
345             # Set up the child's file descriptors.
346 5 100       431 if(ref $options->{"stdin"}) {
    50          
    50          
347             # Also covers "new". See above.
348 2         26 untie *STDIN; # Some programs, like mod_perl, think it's great to tie packages to these file handles.
349 2 50       354 open STDIN, "<&", $options->{"stdin"} or die "dup: $!\n";
350 2         22 close $options->{"stdin"};
351             } elsif($options->{"stdin"} eq "close") {
352             # Need a placeholder file handle so the next open() doesn't take the slot.
353 0 0       0 open STDIN, "<", "/dev/null" or die "/dev/null: $!\n";
354             } elsif($options->{"stdin"} eq "default") {
355             # Empty
356             } else {
357 0         0 die "Can't happen!";
358             }
359 5 100       261 if(ref $options->{"stdout"}) {
    50          
    50          
360             # Also covers "new". See above.
361 4         72 untie *STDOUT; # Some programs, like mod_perl, think it's great to tie packages to these file handles.
362 4 50       1032 open STDOUT, ">&", $options->{"stdout"} or die "dup: $!\n";
363 4         49 close $options->{"stdout"};
364             } elsif($options->{"stdout"} eq "close") {
365             # Need a placeholder file handle so the next open() doesn't take the slot.
366 0 0       0 open STDOUT, ">", "/dev/null" or die "/dev/null: $!\n";
367             } elsif($options->{"stdout"} eq "default") {
368             # Empty
369             } else {
370 0         0 die "Can't happen!";
371             }
372 5 50       176 if(ref $options->{"stderr"}) {
    50          
    50          
373             # Also covers "new". See above.
374 0         0 untie *STDERR; # Some programs, like mod_perl, think it's great to tie packages to these file handles.
375 0 0       0 open STDERR, ">&", $options->{"stderr"} or die "dup: $!\n";
376 0         0 close $options->{"stderr"};
377             } elsif($options->{"stderr"} eq "close") {
378             # Need a placeholder file handle so the next open() doesn't take the slot.
379 0 0       0 open STDERR, ">", "/dev/null" or die "/dev/null: $!\n";
380             } elsif($options->{"stderr"} eq "default") {
381             # Empty
382             } else {
383 0         0 die "Can't happen!";
384             }
385              
386             # Lose unnecessary references to these. (This closes the other end of pipes.)
387 5         58 $self->{"stdin"} = undef;
388 5         70 $self->{"stdout"} = undef;
389 5         53 $self->{"stderr"} = undef;
390              
391             # XXX: I didn't document that $error_pipe_w is passed to child_callback because
392             # I haven't decided whether it's a good idea. This allows the caller to unblock
393             # the parent by closing the pipe if it needs to do something that never
394             # returns. However, if it does close the pipe, it must never return. This
395             # allows the caller to take advantage of this module's logic without any
396             # intention to ever call exec() after fork(). It can also be useful for
397             # suspending execution of the parent until the task is complete while reporting
398             # errors to the parent via die(), if it does NOT close the pipe.
399 5 50       73 &{$options->{"child_callback"}}({"error_pipe" => $error_pipe_w}) if $options->{"child_callback"};
  0         0  
400              
401 5 50       74 if($options->{"exec"}) {
402 5 50       32 $options->{"real_arg0"} = ${$options->{"exec"}}[0] unless defined $options->{"real_arg0"};
  5         149  
403              
404             # Untaint just the arg list, not $options->{"real_arg0"}.
405 5 50       29 if($options->{"untaint_args"}) {
406 0         0 foreach my $arg (@{$options->{"exec"}}) {
  0         0  
407 0         0 ($arg) = ($arg =~ qr/^(.*)$/s);
408             }
409             }
410              
411             {
412             # exec {$arg0} @args will never add the shell interpreter. This handles the
413             # errors from exec, so tell Perl not to report them.
414 6     6   18186 no warnings 'exec';
  6         12  
  6         9516  
  5         27  
415 5         9 exec {$options->{"real_arg0"}} @{$options->{"exec"}};
  5         11  
  5         0  
416             }
417 0         0 die "$options->{'real_arg0'}: $!\n";
418             }
419              
420 0 0       0 if($options->{"fork"}) {
421 0         0 return ();
422             }
423              
424 0         0 die "Can't happen! No action specified for child process, checked in parent.";
425             };
426 0 0       0 if($@) {
427             # This exit status isn't returned to the caller because the error in the pipe
428             # causes a die in the parent. However, if it's non-zero it'll trigger the
429             # warning in $self->DESTROY(). If the write fails, which probably means
430             # something went horribly wrong, we'll let that warning happen, although it
431             # won't make a lot of sense. XXX: Should this write failure be handled better?
432 0 0       0 print $error_pipe_w $@ or POSIX::exit(1);
433 0         0 POSIX::_exit(0);
434             }
435 0         0 die "Can't happen!";
436             }
437              
438             sub wait {
439 13     13 0 83 my ($self, $options) = @_;
440              
441             # Waiting on a PID twice can be bad because the kernel reuses PIDs, so if this
442             # program forks another child, we could accidentally wait on it.
443 13 50       166 die "Child was already waited on\n" if defined $self->{"exit_status"};
444              
445 13 50 33     183 unless($options->{"no_close"} or $options->{"nonblock"}) {
446             # Close the pipes so the child receives EOF on stdin and isn't blocking to
447             # write to stdout or stderr. Ignore errors because these may already already be
448             # closed.
449 13 100       79 close $self->{"stdin"} if ref $self->{"stdin"};
450 13 100       67 close $self->{"stdout"} if ref $self->{"stdout"};
451 13 50       47 close $self->{"stderr"} if ref $self->{"stderr"};
452             }
453              
454 13 50       6980 my $waitpid = waitpid($self->{"child_pid"}, ($options->{"nonblock"} ? &WNOHANG : 0));
455 13 50       97 die "Child was already waited on without calling the wait method\n" if $waitpid == -1;
456 13 50       45 return undef if $waitpid == 0; # Child didn't exit yet.
457 13         178 $self->{"exit_status"} = $?;
458 13         35 $? = -1; # Invalidate $? so callers don't rely on it since the internal behavior of this method may change in the future.
459 13 50       62 warn sprintf("Exit status was %s (%s)", $self->{"exit_status"}, ($self->{"exit_status"} >> 8)) if $self->{"debug"};
460 13         114 return 1;
461             }
462              
463             sub DESTROY {
464 13     13   23 my ($self) = @_;
465              
466             # need_wait is set in the parent when the fork() is successful. This prevents
467             # weird stuff from the object's destruction in the child or when an error
468             # happens before fork(). As far as implementation, no_autowait means the caller
469             # expects the child to out-live the object.
470 13 100 33     166 if($self->{"need_wait"} and not $self->{"no_autowait"} and not defined $self->{"exit_status"}) {
      66        
471 1         23 $self->wait(); # Wait for the child so we don't accidentally leave a zombie process.
472             }
473              
474 13 50 33     46 if($self->{"exit_status"} and not $self->{"fetched_exit_status"}) {
475             # Non-zero exit status, and the caller didn't inspect the exit status, and the
476             # caller didn't specify no_autowait (which may imply the exit status might not
477             # be meaningful). It's bad practice not to inspect the exit status, so we'll
478             # warn about it. It's easy enough for the caller to quiet this warning.
479 0         0 warn sprintf("Exit status was %s (%s) in " . __PACKAGE__ . ", but nothing ever checked it. (Call exit_status() to check it.)\n",
480             $self->{"exit_status"}, ($self->{"exit_status"} >> 8));
481             }
482 13         179 return ();
483             }
484              
485             sub stdin {
486 3     3 0 102 return $_[0]->{"stdin"};
487             }
488              
489             sub stdout {
490 5     5 0 120 return $_[0]->{"stdout"};
491             }
492              
493             sub stderr {
494 0     0 0 0 return $_[0]->{"stderr"};
495             }
496              
497             sub child_pid {
498 0     0 0 0 return $_[0]->{"child_pid"};
499             }
500              
501             sub exit_status {
502 12 50   12 1 74 $_[0]->{"fetched_exit_status"} = 1 if defined $_[0]->{"exit_status"};
503 12         130 return $_[0]->{"exit_status"};
504             }
505              
506              
507             # Functional (non-OOP) subs follow.
508              
509             # Private sub.
510             sub set_cloexec {
511 60     60 0 106 my ($fh) = @_;
512 60         73 my $fcntl;
513 60 50       328 $fcntl = fcntl($fh, F_GETFL, 0) or die "fcntl: $!\n";
514 60 50       452 $fcntl = fcntl($fh, F_SETFL, $fcntl | FD_CLOEXEC) or die "fnctl: $!\n";
515             }
516              
517             # Equivalent to `@exec`, but with the safety of Proc::SafeExec.
518             sub backtick {
519 0     0 1 0 my @exec = @_;
520              
521 0         0 my $command = new Proc::SafeExec({
522             "exec" => [@_],
523             "stdout" => "new",
524             });
525 0         0 my $stdout = $command->stdout();
526 0         0 local $/ = undef;
527 0         0 my $output = <$stdout>;
528 0         0 $command->wait();
529              
530             # If the caller uses scalar context, return just $output and warn on nonzero
531             # exit status.
532 0 0       0 return ($output, $command->exit_status()) if wantarray;
533 0         0 return $output;
534             }
535              
536             sub test {
537 6     6 1 1056 my $test = "";
538              
539             # Test case for ls | sort > /tmp/Proc-SafeExec-test1.txt
540 6         1710 my ($output_fh, $output_filename) = File::Temp::tempfile("Proc-SafeExec.XXXXXXXXXXXXXXXX", "SUFFIX" => ".txt", "DIR" => File::Spec->tmpdir());
541 6         4248 eval {
542 6         84 my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => "new"});
543 5         1345 my $sort = new Proc::SafeExec({"exec" => ["sort"], "stdin" => $ls->stdout(), "stdout" => $output_fh});
544 4 50       128 $ls->wait() or die '$ls->wait() returned false';
545 4 50       28 $sort->wait() or die '$sort->wait() returned false';
546 4 50       52 $ls->exit_status() and die "ls exited with status " . $ls->exit_status();
547 4 50       16 $sort->exit_status() and die "sort exited with status " . $sort->exit_status();
548             };
549 4         572 unlink($output_filename);
550 4 50       32 $test .= "$@not " if $@;
551 4         32 $test .= "ok - ls | sort > /tmp/Proc-SafeExec-test1.txt\n";
552              
553             # Another test case for ls | sort > /tmp/Proc-SafeExec-test2.txt
554             # This one will deadlock if the parent doesn't close stdin.
555 4         404 ($output_fh, $output_filename) = File::Temp::tempfile("Proc-SafeExec.XXXXXXXXXXXXXXXX", "SUFFIX" => ".txt", "DIR" => File::Spec->tmpdir());
556 4         2768 eval {
557 4         84 my $sort = new Proc::SafeExec({"exec" => ["sort"], "stdin" => "new", "stdout" => $output_fh});
558 3         132 my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => $sort->stdin()});
559 2 50       80 $ls->wait() or die '$ls->wait() returned false';
560 2 50       34 $sort->wait() or die '$sort->wait() returned false';
561 2 50       38 $ls->exit_status() and die "ls exited with status " . $ls->exit_status();
562 2 50       20 $sort->exit_status() and die "sort exited with status " . $sort->exit_status();
563             };
564 2         252 unlink($output_filename);
565 2 50       14 $test .= "$@not " if $@;
566 2         18 $test .= "ok - ls | sort > /tmp/Proc-SafeExec-test2.txt\n";
567              
568             # Test case for exec failure.
569 2         4 my $message;
570 2         14 eval {
571 2         8 eval {
572 2         58 my $nope = new Proc::SafeExec({"exec" => ["/nonexistent"]});
573             };
574 1 50       22 die "Testing exec failure should have died." unless $@;
575 1         6 $message = $@;
576 1         7 chomp $message;
577             };
578 1 50       7 $test .= "$@not " if $@;
579 1         8 $test .= "ok - testing exec failure: $message\n";
580              
581 1         66 return $test;
582             }
583              
584             1