7 use constant IS_VMS => $^O eq 'VMS' ? 1 : 0;
8 use constant IS_WIN32 => $^O eq 'MSWin32' ? 1 : 0;
9 use constant IS_WIN98 => (IS_WIN32 and !Win32::IsWinNT()) ? 1 : 0;
10 use constant ALARM_CLASS => __PACKAGE__ . '::TimeOut';
11 use constant SPECIAL_CHARS => qw[< > | &];
12 use constant QUOTE => do { IS_WIN32 ? q["] : q['] };
15 use vars qw[ @ISA $VERSION @EXPORT_OK $VERBOSE $DEBUG
16 $USE_IPC_RUN $USE_IPC_OPEN3 $CAN_USE_RUN_FORKED $WARN
17 $INSTANCES $ALLOW_NULL_ARGS
25 $USE_IPC_RUN = IS_WIN32 && !IS_WIN98;
26 $USE_IPC_OPEN3 = not IS_VMS;
29 $CAN_USE_RUN_FORKED = 0;
31 require POSIX; POSIX->import();
32 require IPC::Open3; IPC::Open3->import();
33 require IO::Select; IO::Select->import();
34 require IO::Handle; IO::Handle->import();
35 require FileHandle; FileHandle->import();
37 require Time::HiRes; Time::HiRes->import();
38 require Win32 if IS_WIN32;
40 $CAN_USE_RUN_FORKED = $@ || !IS_VMS && !IS_WIN32;
43 my $wait_start_time = Time::HiRes::clock_gettime(&Time::HiRes::CLOCK_MONOTONIC);
53 @EXPORT_OK = qw[can_run run run_forked QUOTE];
58 use Params::Check qw[check];
59 use Text::ParseWords (); # import ONLY if needed!
60 use Module::Load::Conditional qw[can_load];
61 use Locale::Maketext::Simple Style => 'gettext';
67 IPC::Cmd - finding and running system commands made easy
71 use IPC::Cmd qw[can_run run run_forked];
73 my $full_path = can_run('wget') or warn 'wget is not installed!';
75 ### commands can be arrayrefs or strings ###
76 my $cmd = "$full_path -b theregister.co.uk";
77 my $cmd = [$full_path, '-b', 'theregister.co.uk'];
79 ### in scalar context ###
81 if( scalar run( command => $cmd,
86 print "fetched webpage successfully: $buffer\n";
90 ### in list context ###
91 my( $success, $error_message, $full_buf, $stdout_buf, $stderr_buf ) =
92 run( command => $cmd, verbose => 0 );
95 print "this is what the command printed:\n";
96 print join "", @$full_buf;
99 ### run_forked example ###
100 my $result = run_forked("$full_path -q -O - theregister.co.uk", {'timeout' => 20});
101 if ($result->{'exit_code'} eq 0 && !$result->{'timeout'}) {
102 print "this is what wget returned:\n";
103 print $result->{'stdout'};
106 ### check for features
107 print "IPC::Open3 available: " . IPC::Cmd->can_use_ipc_open3;
108 print "IPC::Run available: " . IPC::Cmd->can_use_ipc_run;
109 print "Can capture buffer: " . IPC::Cmd->can_capture_buffer;
111 ### don't have IPC::Cmd be verbose, ie don't print to stdout or
112 ### stderr when running commands -- default is '0'
113 $IPC::Cmd::VERBOSE = 0;
118 IPC::Cmd allows you to run commands platform independently,
119 interactively if desired, but have them still work.
121 The C<can_run> function can tell you if a certain binary is installed
122 and if so where, whereas the C<run> function can actually execute any
123 of the commands you give it and give you a clear return value, as well
124 as adhere to your verbosity settings.
128 =head2 $ipc_run_version = IPC::Cmd->can_use_ipc_run( [VERBOSE] )
130 Utility function that tells you if C<IPC::Run> is available.
131 If the C<verbose> flag is passed, it will print diagnostic messages
132 if L<IPC::Run> can not be found or loaded.
137 sub can_use_ipc_run {
139 my $verbose = shift || 0;
141 ### IPC::Run doesn't run on win98
144 ### if we don't have ipc::run, we obviously can't use it.
145 return unless can_load(
146 modules => { 'IPC::Run' => '0.55' },
147 verbose => ($WARN && $verbose),
150 ### otherwise, we're good to go
151 return $IPC::Run::VERSION;
154 =head2 $ipc_open3_version = IPC::Cmd->can_use_ipc_open3( [VERBOSE] )
156 Utility function that tells you if C<IPC::Open3> is available.
157 If the verbose flag is passed, it will print diagnostic messages
158 if C<IPC::Open3> can not be found or loaded.
163 sub can_use_ipc_open3 {
165 my $verbose = shift || 0;
167 ### IPC::Open3 is not working on VMS because of a lack of fork.
170 ### IPC::Open3 works on every non-VMS platform, but it can't
171 ### capture buffers on win32 :(
172 return unless can_load(
173 modules => { map {$_ => '0.0'} qw|IPC::Open3 IO::Select Symbol| },
174 verbose => ($WARN && $verbose),
177 return $IPC::Open3::VERSION;
180 =head2 $bool = IPC::Cmd->can_capture_buffer
182 Utility function that tells you if C<IPC::Cmd> is capable of
183 capturing buffers in it's current configuration.
187 sub can_capture_buffer {
190 return 1 if $USE_IPC_RUN && $self->can_use_ipc_run;
191 return 1 if $USE_IPC_OPEN3 && $self->can_use_ipc_open3;
195 =head2 $bool = IPC::Cmd->can_use_run_forked
197 Utility function that tells you if C<IPC::Cmd> is capable of
198 providing C<run_forked> on the current platform.
202 =head2 $path = can_run( PROGRAM );
204 C<can_run> takes only one argument: the name of a binary you wish
205 to locate. C<can_run> works much like the unix binary C<which> or the bash
206 command C<type>, which scans through your path, looking for the requested
209 Unlike C<which> and C<type>, this function is platform independent and
210 will also work on, for example, Win32.
212 If called in a scalar context it will return the full path to the binary
213 you asked for if it was found, or C<undef> if it was not.
215 If called in a list context and the global variable C<$INSTANCES> is a true
216 value, it will return a list of the full paths to instances
217 of the binary where found in C<PATH>, or an empty list if it was not found.
224 # a lot of VMS executables have a symbol defined
226 if ( $^O eq 'VMS' ) {
228 my $syms = VMS::DCLsym->new;
229 return $command if scalar $syms->getsym( uc $command );
233 require ExtUtils::MakeMaker;
237 if( File::Spec->file_name_is_absolute($command) ) {
238 return MM->maybe_command($command);
245 next if ! $dir || ! -d $dir;
246 my $abs = File::Spec->catfile( IS_WIN32 ? Win32::GetShortPathName( $dir ) : $dir, $command);
247 push @possibles, $abs if $abs = MM->maybe_command($abs);
250 return @possibles if wantarray and $INSTANCES;
251 return shift @possibles;
254 =head2 $ok | ($ok, $err, $full_buf, $stdout_buff, $stderr_buff) = run( command => COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] );
256 C<run> takes 4 arguments:
262 This is the command to execute. It may be either a string or an array
264 This is a required argument.
266 See L<"Caveats"> for remarks on how commands are parsed and their
271 This controls whether all output of a command should also be printed
272 to STDOUT/STDERR or should only be trapped in buffers (NOTE: buffers
273 require L<IPC::Run> to be installed, or your system able to work with
276 It will default to the global setting of C<$IPC::Cmd::VERBOSE>,
277 which by default is 0.
281 This will hold all the output of a command. It needs to be a reference
283 Note that this will hold both the STDOUT and STDERR messages, and you
284 have no way of telling which is which.
285 If you require this distinction, run the C<run> command in list context
286 and inspect the individual buffers.
288 Of course, this requires that the underlying call supports buffers. See
289 the note on buffers above.
293 Sets the maximum time the command is allowed to run before aborting,
294 using the built-in C<alarm()> call. If the timeout is triggered, the
295 C<errorcode> in the return value will be set to an object of the
296 C<IPC::Cmd::TimeOut> class. See the L<"error message"> section below for
299 Defaults to C<0>, meaning no timeout is set.
303 C<run> will return a simple C<true> or C<false> when called in scalar
305 In list context, you will be returned a list of the following items:
311 A simple boolean indicating if the command executed without errors or
316 If the first element of the return value (C<success>) was 0, then some
317 error occurred. This second element is the error message the command
318 you requested exited with, if available. This is generally a pretty
319 printed value of C<$?> or C<$@>. See C<perldoc perlvar> for details on
320 what they can contain.
321 If the error was a timeout, the C<error message> will be prefixed with
322 the string C<IPC::Cmd::TimeOut>, the timeout class.
326 This is an array reference containing all the output the command
328 Note that buffers are only available if you have L<IPC::Run> installed,
329 or if your system is able to work with L<IPC::Open3> -- see below).
330 Otherwise, this element will be C<undef>.
334 This is an array reference containing all the output sent to STDOUT the
335 command generated. The notes from L<"full_buffer"> apply.
339 This is an arrayreference containing all the output sent to STDERR the
340 command generated. The notes from L<"full_buffer"> apply.
345 See the L<"HOW IT WORKS"> section below to see how C<IPC::Cmd> decides
346 what modules or function calls to use when issuing a command.
350 { my @acc = qw[ok error _fds];
352 ### autogenerate accessors ###
353 for my $key ( @acc ) {
355 *{__PACKAGE__."::$key"} = sub {
356 $_[0]->{$key} = $_[1] if @_ > 1;
357 return $_[0]->{$key};
362 sub can_use_run_forked {
363 return $CAN_USE_RUN_FORKED eq "1";
366 sub get_monotonic_time {
367 if ($HAVE_MONOTONIC) {
368 return Time::HiRes::clock_gettime(&Time::HiRes::CLOCK_MONOTONIC);
375 sub adjust_monotonic_start_time {
376 my ($ref_vars, $now, $previous) = @_;
378 # workaround only for those systems which don't have
379 # Time::HiRes::CLOCK_MONOTONIC (Mac OSX in particular)
380 return if $HAVE_MONOTONIC;
382 # don't have previous monotonic value (only happens once
383 # in the beginning of the program execution)
384 return unless $previous;
386 my $time_diff = $now - $previous;
388 # adjust previously saved time with the skew value which is
389 # either negative when clock moved back or more than 5 seconds --
390 # assuming that event loop does happen more often than once
391 # per five seconds, which might not be always true (!) but
392 # hopefully that's ok, because it's just a workaround
393 if ($time_diff > 5 || $time_diff < 0) {
394 foreach my $ref_var (@{$ref_vars}) {
395 if (defined($$ref_var)) {
396 $$ref_var = $$ref_var + $time_diff;
402 # incompatible with POSIX::SigAction
404 sub install_layered_signal {
405 my ($s, $handler_code) = @_;
407 my %available_signals = map {$_ => 1} keys %SIG;
409 Carp::confess("install_layered_signal got nonexistent signal name [$s]")
410 unless defined($available_signals{$s});
411 Carp::confess("install_layered_signal expects coderef")
412 if !ref($handler_code) || ref($handler_code) ne 'CODE';
414 my $previous_handler = $SIG{$s};
416 my $sig_handler = sub {
417 my ($called_sig_name, @sig_param) = @_;
419 # $s is a closure referring to real signal name
420 # for which this handler is being installed.
421 # it is used to distinguish between
422 # real signal handlers and aliased signal handlers
423 my $signal_name = $s;
425 # $called_sig_name is a signal name which
426 # was passed to this signal handler;
427 # it doesn't equal $signal_name in case
428 # some signal handlers in %SIG point
429 # to other signal handler (CHLD and CLD,
432 # initial signal handler for aliased signal
433 # calls some other signal handler which
434 # should not execute the same handler_code again
435 if ($called_sig_name eq $signal_name) {
436 $handler_code->($signal_name);
439 # run original signal handler if any (including aliased)
441 if (ref($previous_handler)) {
442 $previous_handler->($called_sig_name, @sig_param);
446 $SIG{$s} = $sig_handler;
449 # give process a chance sending TERM,
450 # waiting for a while (2 seconds)
451 # and killing it with KILL
453 my ($pid, $opts) = @_;
457 $opts = {} unless $opts;
458 $opts->{'wait_time'} = 2 unless defined($opts->{'wait_time'});
459 $opts->{'first_kill_type'} = 'just_process' unless $opts->{'first_kill_type'};
460 $opts->{'final_kill_type'} = 'just_process' unless $opts->{'final_kill_type'};
462 if ($opts->{'first_kill_type'} eq 'just_process') {
465 elsif ($opts->{'first_kill_type'} eq 'process_group') {
470 my $child_finished = 0;
472 my $wait_start_time = get_monotonic_time();
474 my $previous_monotonic_value;
477 $previous_monotonic_value = $now;
478 $now = get_monotonic_time();
480 adjust_monotonic_start_time([\$wait_start_time], $now, $previous_monotonic_value);
482 if ($now > $wait_start_time + $opts->{'wait_time'}) {
487 my $waitpid = waitpid($pid, POSIX::WNOHANG);
489 if ($waitpid eq -1) {
495 Time::HiRes::usleep(250000); # quarter of a second
498 if (!$child_finished) {
499 if ($opts->{'final_kill_type'} eq 'just_process') {
502 elsif ($opts->{'final_kill_type'} eq 'process_group') {
509 my ($cmd, $opts) = @_;
511 $opts = {} unless $opts;
513 my $child_in = FileHandle->new;
514 my $child_out = FileHandle->new;
515 my $child_err = FileHandle->new;
516 $child_out->autoflush(1);
517 $child_err->autoflush(1);
519 my $pid = open3($child_in, $child_out, $child_err, $cmd);
521 # push my child's pid to our parent
522 # so in case i am killed parent
523 # could stop my child (search for
524 # child_child_pid in parent code)
525 if ($opts->{'parent_info'}) {
526 my $ps = $opts->{'parent_info'};
527 print $ps "spawned $pid\n";
530 if ($child_in && $child_out->opened && $opts->{'child_stdin'}) {
532 # If the child process dies for any reason,
533 # the next write to CHLD_IN is likely to generate
534 # a SIGPIPE in the parent, which is fatal by default.
535 # So you may wish to handle this signal.
537 # from http://perldoc.perl.org/IPC/Open3.html,
538 # absolutely needed to catch piped commands errors.
540 local $SIG{'PIPE'} = sub { 1; };
542 print $child_in $opts->{'child_stdin'};
547 'out' => $child_out->fileno,
548 'err' => $child_err->fileno,
549 $child_out->fileno => {
550 'parent_socket' => $opts->{'parent_stdout'},
551 'scalar_buffer' => "",
552 'child_handle' => $child_out,
553 'block_size' => ($child_out->stat)[11] || 1024,
555 $child_err->fileno => {
556 'parent_socket' => $opts->{'parent_stderr'},
557 'scalar_buffer' => "",
558 'child_handle' => $child_err,
559 'block_size' => ($child_err->stat)[11] || 1024,
563 my $select = IO::Select->new();
564 $select->add($child_out, $child_err);
566 # pass any signal to the child
567 # effectively creating process
568 # strongly attached to the child:
569 # it will terminate only after child
570 # has terminated (except for SIGKILL,
571 # which is specially handled)
572 foreach my $s (keys %SIG) {
576 $SIG{$s} = $sig_handler;
578 $SIG{$s} = $sig_handler;
581 my $child_finished = 0;
583 my $got_sig_child = 0;
584 $SIG{'CHLD'} = sub { $got_sig_child = time(); };
586 while(!$child_finished && ($child_out->opened || $child_err->opened)) {
588 # parent was killed otherwise we would have got
589 # the same signal as parent and process it same way
590 if (getppid() eq "1") {
592 # end my process group with all the children
593 # (i am the process group leader, so my pid
594 # equals to the process group id)
596 # same thing which is done
597 # with $opts->{'clean_up_children'}
605 if ($got_sig_child) {
606 if (time() - $got_sig_child > 1) {
607 # select->can_read doesn't return 0 after SIG_CHLD
609 # "On POSIX-compliant platforms, SIGCHLD is the signal
610 # sent to a process when a child process terminates."
611 # http://en.wikipedia.org/wiki/SIGCHLD
613 # nevertheless kill KILL wouldn't break anything here
620 Time::HiRes::usleep(1);
622 foreach my $fd ($select->can_read(1/100)) {
623 my $str = $child_output->{$fd->fileno};
624 Carp::confess("child stream not found: $fd") unless $str;
627 my $count = $fd->sysread($data, $str->{'block_size'});
630 if ($str->{'parent_socket'}) {
631 my $ph = $str->{'parent_socket'};
635 $str->{'scalar_buffer'} .= $data;
638 elsif ($count eq 0) {
639 $select->remove($fd);
643 Carp::confess("error during sysread: " . $!);
648 my $waitpid_ret = waitpid($pid, 0);
650 my $exit_value = $real_exit >> 8;
652 # since we've successfully reaped the child,
653 # let our parent know about this.
655 if ($opts->{'parent_info'}) {
656 my $ps = $opts->{'parent_info'};
658 # child was killed, inform parent
659 if ($real_exit & 127) {
660 print $ps "$pid killed with " . ($real_exit & 127) . "\n";
663 print $ps "reaped $pid\n";
666 if ($opts->{'parent_stdout'} || $opts->{'parent_stderr'}) {
671 'stdout' => $child_output->{$child_output->{'out'}}->{'scalar_buffer'},
672 'stderr' => $child_output->{$child_output->{'err'}}->{'scalar_buffer'},
673 'exit_code' => $exit_value,
678 =head2 $hashref = run_forked( COMMAND, { child_stdin => SCALAR, timeout => DIGIT, stdout_handler => CODEREF, stderr_handler => CODEREF} );
680 C<run_forked> is used to execute some program or a coderef,
681 optionally feed it with some input, get its return code
682 and output (both stdout and stderr into separate buffers).
683 In addition, it allows to terminate the program
684 if it takes too long to finish.
686 The important and distinguishing feature of run_forked
687 is execution timeout which at first seems to be
688 quite a simple task but if you think
689 that the program which you're spawning
690 might spawn some children itself (which
691 in their turn could do the same and so on)
692 it turns out to be not a simple issue.
694 C<run_forked> is designed to survive and
695 successfully terminate almost any long running task,
696 even a fork bomb in case your system has the resources
697 to survive during given timeout.
699 This is achieved by creating separate watchdog process
700 which spawns the specified program in a separate
701 process session and supervises it: optionally
702 feeds it with input, stores its exit code,
703 stdout and stderr, terminates it in case
704 it runs longer than specified.
706 Invocation requires the command to be executed or a coderef and optionally a hashref of options:
712 Specify in seconds how long to run the command before it is killed with SIG_KILL (9),
713 which effectively terminates it and all of its children (direct or indirect).
717 Specify some text that will be passed into the C<STDIN> of the executed program.
719 =item C<stdout_handler>
721 Coderef of a subroutine to call when a portion of data is received on
722 STDOUT from the executing program.
724 =item C<stderr_handler>
726 Coderef of a subroutine to call when a portion of data is received on
727 STDERR from the executing program.
730 =item C<discard_output>
732 Discards the buffering of the standard output and standard errors for return by run_forked().
733 With this option you have to use the std*_handlers to read what the command outputs.
734 Useful for commands that send a lot of output.
736 =item C<terminate_on_parent_sudden_death>
738 Enable this option if you wish all spawned processes to be killed if the initially spawned
739 process (the parent) is killed or dies without waiting for child processes.
743 C<run_forked> will return a HASHREF with the following keys:
749 The exit code of the executed program.
753 The number of seconds the program ran for before being terminated, or 0 if no timeout occurred.
757 Holds the standard output of the executed command (or empty string if
758 there was no STDOUT output or if C<discard_output> was used; it's always defined!)
762 Holds the standard error of the executed command (or empty string if
763 there was no STDERR output or if C<discard_output> was used; it's always defined!)
767 Holds the standard output and error of the executed command merged into one stream
768 (or empty string if there was no output at all or if C<discard_output> was used; it's always defined!)
772 Holds some explanation in the case of an error.
779 ### container to store things in
780 my $self = bless {}, __PACKAGE__;
782 if (!can_use_run_forked()) {
783 Carp::carp("run_forked is not available: $CAN_USE_RUN_FORKED");
789 my ($cmd, $opts) = @_;
790 if (ref($cmd) eq 'ARRAY') {
791 $cmd = join(" ", @{$cmd});
795 Carp::carp("run_forked expects command to run");
799 $opts = {} unless $opts;
800 $opts->{'timeout'} = 0 unless $opts->{'timeout'};
801 $opts->{'terminate_wait_time'} = 2 unless defined($opts->{'terminate_wait_time'});
803 # turned on by default
804 $opts->{'clean_up_children'} = 1 unless defined($opts->{'clean_up_children'});
806 # sockets to pass child stdout to parent
807 my $child_stdout_socket;
808 my $parent_stdout_socket;
810 # sockets to pass child stderr to parent
811 my $child_stderr_socket;
812 my $parent_stderr_socket;
814 # sockets for child -> parent internal communication
815 my $child_info_socket;
816 my $parent_info_socket;
818 socketpair($child_stdout_socket, $parent_stdout_socket, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC) ||
819 Carp::confess ("socketpair: $!");
820 socketpair($child_stderr_socket, $parent_stderr_socket, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC) ||
821 Carp::confess ("socketpair: $!");
822 socketpair($child_info_socket, $parent_info_socket, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC) ||
823 Carp::confess ("socketpair: $!");
825 $child_stdout_socket->autoflush(1);
826 $parent_stdout_socket->autoflush(1);
827 $child_stderr_socket->autoflush(1);
828 $parent_stderr_socket->autoflush(1);
829 $child_info_socket->autoflush(1);
830 $parent_info_socket->autoflush(1);
832 my $start_time = get_monotonic_time();
838 close($parent_stdout_socket);
839 close($parent_stderr_socket);
840 close($parent_info_socket);
844 # prepare sockets to read from child
847 fcntl($child_stdout_socket, POSIX::F_GETFL, $flags) || Carp::confess "can't fnctl F_GETFL: $!";
848 $flags |= POSIX::O_NONBLOCK;
849 fcntl($child_stdout_socket, POSIX::F_SETFL, $flags) || Carp::confess "can't fnctl F_SETFL: $!";
852 fcntl($child_stderr_socket, POSIX::F_GETFL, $flags) || Carp::confess "can't fnctl F_GETFL: $!";
853 $flags |= POSIX::O_NONBLOCK;
854 fcntl($child_stderr_socket, POSIX::F_SETFL, $flags) || Carp::confess "can't fnctl F_SETFL: $!";
857 fcntl($child_info_socket, POSIX::F_GETFL, $flags) || Carp::confess "can't fnctl F_GETFL: $!";
858 $flags |= POSIX::O_NONBLOCK;
859 fcntl($child_info_socket, POSIX::F_SETFL, $flags) || Carp::confess "can't fnctl F_SETFL: $!";
861 # print "child $pid started\n";
864 $child_stdout_socket->fileno => {
865 'scalar_buffer' => "",
866 'child_handle' => $child_stdout_socket,
867 'block_size' => ($child_stdout_socket->stat)[11] || 1024,
868 'protocol' => 'stdout',
870 $child_stderr_socket->fileno => {
871 'scalar_buffer' => "",
872 'child_handle' => $child_stderr_socket,
873 'block_size' => ($child_stderr_socket->stat)[11] || 1024,
874 'protocol' => 'stderr',
876 $child_info_socket->fileno => {
877 'scalar_buffer' => "",
878 'child_handle' => $child_info_socket,
879 'block_size' => ($child_info_socket->stat)[11] || 1024,
880 'protocol' => 'info',
884 my $select = IO::Select->new();
885 $select->add($child_stdout_socket, $child_stderr_socket, $child_info_socket);
887 my $child_timedout = 0;
888 my $child_finished = 0;
889 my $child_stdout = '';
890 my $child_stderr = '';
891 my $child_merged = '';
892 my $child_exit_code = 0;
893 my $child_killed_by_signal = 0;
896 my $last_parent_check = 0;
897 my $got_sig_child = 0;
898 my $got_sig_quit = 0;
899 my $orig_sig_child = $SIG{'CHLD'};
901 $SIG{'CHLD'} = sub { $got_sig_child = get_monotonic_time(); };
903 if ($opts->{'terminate_on_signal'}) {
904 install_layered_signal($opts->{'terminate_on_signal'}, sub { $got_sig_quit = time(); });
909 my $previous_monotonic_value;
911 while (!$child_finished) {
912 $previous_monotonic_value = $now;
913 $now = get_monotonic_time();
915 adjust_monotonic_start_time([\$start_time, \$last_parent_check, \$got_sig_child], $now, $previous_monotonic_value);
917 if ($opts->{'terminate_on_parent_sudden_death'}) {
918 # check for parent once each five seconds
919 if ($now > $last_parent_check + 5) {
920 if (getppid() eq "1") {
922 'first_kill_type' => 'process_group',
923 'final_kill_type' => 'process_group',
924 'wait_time' => $opts->{'terminate_wait_time'}
929 $last_parent_check = $now;
933 # user specified timeout
934 if ($opts->{'timeout'}) {
935 if ($now > $start_time + $opts->{'timeout'}) {
937 'first_kill_type' => 'process_group',
938 'final_kill_type' => 'process_group',
939 'wait_time' => $opts->{'terminate_wait_time'}
945 # give OS 10 seconds for correct return of waitpid,
946 # kill process after that and finish wait loop;
947 # shouldn't ever happen -- remove this code?
948 if ($got_sig_child) {
949 if ($now > $got_sig_child + 10) {
950 print STDERR "waitpid did not return -1 for 10 seconds after SIG_CHLD, killing [$pid]\n";
958 'first_kill_type' => 'process_group',
959 'final_kill_type' => 'process_group',
960 'wait_time' => $opts->{'terminate_wait_time'}
965 my $waitpid = waitpid($pid, POSIX::WNOHANG);
967 # child finished, catch it's exit status
968 if ($waitpid ne 0 && $waitpid ne -1) {
969 $child_exit_code = $? >> 8;
972 if ($waitpid eq -1) {
977 push @{$ready_fds}, $select->can_read(1/100);
979 READY_FDS: while (scalar(@{$ready_fds})) {
980 my $fd = shift @{$ready_fds};
981 $ready_fds = [grep {$_ ne $fd} @{$ready_fds}];
983 my $str = $child_output->{$fd->fileno};
984 Carp::confess("child stream not found: $fd") unless $str;
987 my $count = $fd->sysread($data, $str->{'block_size'});
990 # extract all the available lines and store the rest in temporary buffer
991 if ($data =~ /(.+\n)([^\n]*)/so) {
992 $data = $str->{'scalar_buffer'} . $1;
993 $str->{'scalar_buffer'} = $2 || "";
996 $str->{'scalar_buffer'} .= $data;
1000 elsif ($count eq 0) {
1001 $select->remove($fd);
1003 if ($str->{'scalar_buffer'}) {
1004 $data = $str->{'scalar_buffer'} . "\n";
1008 Carp::confess("error during sysread on [$fd]: " . $!);
1011 # $data contains only full lines (or last line if it was unfinished read
1012 # or now new-line in the output of the child); dat is processed
1013 # according to the "protocol" of socket
1014 if ($str->{'protocol'} eq 'info') {
1015 if ($data =~ /^spawned ([0-9]+?)\n(.*?)/so) {
1016 $child_child_pid = $1;
1019 if ($data =~ /^reaped ([0-9]+?)\n(.*?)/so) {
1020 $child_child_pid = undef;
1023 if ($data =~ /^[\d]+ killed with ([0-9]+?)\n(.*?)/so) {
1024 $child_killed_by_signal = $1;
1028 # we don't expect any other data in info socket, so it's
1029 # some strange violation of protocol, better know about this
1031 Carp::confess("info protocol violation: [$data]");
1034 if ($str->{'protocol'} eq 'stdout') {
1035 if (!$opts->{'discard_output'}) {
1036 $child_stdout .= $data;
1037 $child_merged .= $data;
1040 if ($opts->{'stdout_handler'} && ref($opts->{'stdout_handler'}) eq 'CODE') {
1041 $opts->{'stdout_handler'}->($data);
1044 if ($str->{'protocol'} eq 'stderr') {
1045 if (!$opts->{'discard_output'}) {
1046 $child_stderr .= $data;
1047 $child_merged .= $data;
1050 if ($opts->{'stderr_handler'} && ref($opts->{'stderr_handler'}) eq 'CODE') {
1051 $opts->{'stderr_handler'}->($data);
1055 # process may finish (waitpid returns -1) before
1056 # we've read all of its output because of buffering;
1057 # so try to read all the way it is possible to read
1058 # in such case - this shouldn't be too much (unless
1059 # the buffer size is HUGE -- should introduce
1060 # another counter in such case, maybe later)
1062 push @{$ready_fds}, $select->can_read(1/100) if $child_finished;
1065 Time::HiRes::usleep(1);
1068 # $child_pid_pid is not defined in two cases:
1069 # * when our child was killed before
1070 # it had chance to tell us the pid
1071 # of the child it spawned. we can do
1072 # nothing in this case :(
1073 # * our child successfully reaped its child,
1074 # we have nothing left to do in this case
1076 # defined $child_pid_pid means child's child
1077 # has not died but nobody is waiting for it,
1078 # killing it brutally.
1080 if ($child_child_pid) {
1081 kill_gently($child_child_pid);
1084 # in case there are forks in child which
1085 # do not forward or process signals (TERM) correctly
1086 # kill whole child process group, effectively trying
1087 # not to return with some children or their parts still running
1089 # to be more accurate -- we need to be sure
1090 # that this is process group created by our child
1091 # (and not some other process group with the same pgid,
1092 # created just after death of our child) -- fortunately
1093 # this might happen only when process group ids
1094 # are reused quickly (there are lots of processes
1095 # spawning new process groups for example)
1097 if ($opts->{'clean_up_children'}) {
1101 # print "child $pid finished\n";
1103 close($child_stdout_socket);
1104 close($child_stderr_socket);
1105 close($child_info_socket);
1108 'stdout' => $child_stdout,
1109 'stderr' => $child_stderr,
1110 'merged' => $child_merged,
1111 'timeout' => $child_timedout ? $opts->{'timeout'} : 0,
1112 'exit_code' => $child_exit_code,
1113 'parent_died' => $parent_died,
1114 'killed_by_signal' => $child_killed_by_signal,
1115 'child_pgid' => $pid,
1120 if ($o->{'exit_code'}) {
1121 $err_msg .= "exited with code [$o->{'exit_code'}]\n";
1123 if ($o->{'timeout'}) {
1124 $err_msg .= "ran more than [$o->{'timeout'}] seconds\n";
1126 if ($o->{'parent_died'}) {
1127 $err_msg .= "parent died\n";
1129 if ($o->{'stdout'} && !$opts->{'non_empty_stdout_ok'}) {
1130 $err_msg .= "stdout:\n" . $o->{'stdout'} . "\n";
1132 if ($o->{'stderr'}) {
1133 $err_msg .= "stderr:\n" . $o->{'stderr'} . "\n";
1135 if ($o->{'killed_by_signal'}) {
1136 $err_msg .= "killed by signal [" . $o->{'killed_by_signal'} . "]\n";
1138 $o->{'err_msg'} = $err_msg;
1140 if ($orig_sig_child) {
1141 $SIG{'CHLD'} = $orig_sig_child;
1144 delete($SIG{'CHLD'});
1150 Carp::confess("cannot fork: $!") unless defined($pid);
1152 # create new process session for open3 call,
1153 # so we hopefully can kill all the subprocesses
1154 # which might be spawned in it (except for those
1155 # which do setsid theirselves -- can't do anything
1158 POSIX::setsid() || Carp::confess("Error running setsid: " . $!);
1160 if ($opts->{'child_BEGIN'} && ref($opts->{'child_BEGIN'}) eq 'CODE') {
1161 $opts->{'child_BEGIN'}->();
1164 close($child_stdout_socket);
1165 close($child_stderr_socket);
1166 close($child_info_socket);
1168 my $child_exit_code;
1170 # allow both external programs
1171 # and internal perl calls
1173 $child_exit_code = open3_run($cmd, {
1174 'parent_info' => $parent_info_socket,
1175 'parent_stdout' => $parent_stdout_socket,
1176 'parent_stderr' => $parent_stderr_socket,
1177 'child_stdin' => $opts->{'child_stdin'},
1180 elsif (ref($cmd) eq 'CODE') {
1181 # reopen STDOUT and STDERR for child code:
1182 # https://rt.cpan.org/Ticket/Display.html?id=85912
1183 open STDOUT, '>&', $parent_stdout_socket || Carp::confess("Unable to reopen STDOUT: $!\n");
1184 open STDERR, '>&', $parent_stderr_socket || Carp::confess("Unable to reopen STDERR: $!\n");
1186 $child_exit_code = $cmd->({
1188 'parent_info' => $parent_info_socket,
1189 'parent_stdout' => $parent_stdout_socket,
1190 'parent_stderr' => $parent_stderr_socket,
1191 'child_stdin' => $opts->{'child_stdin'},
1195 print $parent_stderr_socket "Invalid command reference: " . ref($cmd) . "\n";
1196 $child_exit_code = 1;
1199 close($parent_stdout_socket);
1200 close($parent_stderr_socket);
1201 close($parent_info_socket);
1203 if ($opts->{'child_END'} && ref($opts->{'child_END'}) eq 'CODE') {
1204 $opts->{'child_END'}->();
1208 POSIX::_exit $child_exit_code;
1213 ### container to store things in
1214 my $self = bless {}, __PACKAGE__;
1218 ### if the user didn't provide a buffer, we'll store it here.
1221 my($verbose,$cmd,$buffer,$timeout);
1223 verbose => { default => $VERBOSE, store => \$verbose },
1224 buffer => { default => \$def_buf, store => \$buffer },
1225 command => { required => 1, store => \$cmd,
1226 allow => sub { !ref($_[0]) or ref($_[0]) eq 'ARRAY' },
1228 timeout => { default => 0, store => \$timeout },
1231 unless( check( $tmpl, \%hash, $VERBOSE ) ) {
1232 Carp::carp( loc( "Could not validate input: %1",
1233 Params::Check->last_error ) );
1237 $cmd = _quote_args_vms( $cmd ) if IS_VMS;
1239 ### strip any empty elements from $cmd if present
1240 if ( $ALLOW_NULL_ARGS ) {
1241 $cmd = [ grep { defined } @$cmd ] if ref $cmd;
1244 $cmd = [ grep { defined && length } @$cmd ] if ref $cmd;
1247 my $pp_cmd = (ref $cmd ? "@$cmd" : $cmd);
1248 print loc("Running [%1]...\n", $pp_cmd ) if $verbose;
1250 ### did the user pass us a buffer to fill or not? if so, set this
1251 ### flag so we know what is expected of us
1252 ### XXX this is now being ignored. in the future, we could add diagnostic
1253 ### messages based on this logic
1254 #my $user_provided_buffer = $buffer == \$def_buf ? 0 : 1;
1256 ### buffers that are to be captured
1257 my( @buffer, @buff_err, @buff_out );
1260 my $_out_handler = sub {
1262 return unless defined $buf;
1264 print STDOUT $buf if $verbose;
1266 push @buff_out, $buf;
1270 my $_err_handler = sub {
1272 return unless defined $buf;
1274 print STDERR $buf if $verbose;
1276 push @buff_err, $buf;
1280 ### flag to indicate we have a buffer captured
1281 my $have_buffer = $self->can_capture_buffer ? 1 : 0;
1283 ### flag indicating if the subcall went ok
1286 ### don't look at previous errors:
1291 ### we might be having a timeout set
1293 local $SIG{ALRM} = sub { die bless sub {
1295 qq[: Command '$pp_cmd' aborted by alarm after $timeout seconds]
1296 }, ALARM_CLASS } if $timeout;
1297 alarm $timeout || 0;
1299 ### IPC::Run is first choice if $USE_IPC_RUN is set.
1300 if( !IS_WIN32 and $USE_IPC_RUN and $self->can_use_ipc_run( 1 ) ) {
1301 ### ipc::run handlers needs the command as a string or an array ref
1303 $self->_debug( "# Using IPC::Run. Have buffer: $have_buffer" )
1306 $ok = $self->_ipc_run( $cmd, $_out_handler, $_err_handler );
1308 ### since IPC::Open3 works on all platforms, and just fails on
1309 ### win32 for capturing buffers, do that ideally
1310 } elsif ( $USE_IPC_OPEN3 and $self->can_use_ipc_open3( 1 ) ) {
1312 $self->_debug("# Using IPC::Open3. Have buffer: $have_buffer")
1315 ### in case there are pipes in there;
1316 ### IPC::Open3 will call exec and exec will do the right thing
1318 my $method = IS_WIN32 ? '_open3_run_win32' : '_open3_run';
1320 $ok = $self->$method(
1321 $cmd, $_out_handler, $_err_handler, $verbose
1324 ### if we are allowed to run verbose, just dispatch the system command
1326 $self->_debug( "# Using system(). Have buffer: $have_buffer" )
1328 $ok = $self->_system_run( $cmd, $verbose );
1334 ### restore STDIN after duping, or STDIN will be closed for
1335 ### this current perl process!
1336 $self->__reopen_fds( @{ $self->_fds} ) if $self->_fds;
1341 if ( $@ and ref $@ and $@->isa( ALARM_CLASS ) ) {
1342 $err = $@->(); # the error code is an expired alarm
1344 ### another error happened, set by the dispatchub
1346 $err = $self->error;
1350 ### fill the buffer;
1351 $$buffer = join '', @buffer if @buffer;
1353 ### return a list of flags and buffers (if available) in list
1354 ### context, or just a simple 'ok' in scalar
1357 ? ($ok, $err, \@buffer, \@buff_out, \@buff_err)
1364 sub _open3_run_win32 {
1367 my $outhand = shift;
1368 my $errhand = shift;
1373 socketpair($_[0], $_[1], &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC)
1375 shutdown($_[0], 1); # No more writing for reader
1376 shutdown($_[1], 0); # No more reading for writer
1381 local (*TO_CHLD_R, *TO_CHLD_W);
1382 local (*FR_CHLD_R, *FR_CHLD_W);
1383 local (*FR_CHLD_ERR_R, *FR_CHLD_ERR_W);
1385 $pipe->(*TO_CHLD_R, *TO_CHLD_W ) or die $^E;
1386 $pipe->(*FR_CHLD_R, *FR_CHLD_W ) or die $^E;
1387 $pipe->(*FR_CHLD_ERR_R, *FR_CHLD_ERR_W) or die $^E;
1389 my $pid = IPC::Open3::open3('>&TO_CHLD_R', '<&FR_CHLD_W', '<&FR_CHLD_ERR_W', @_);
1391 return ( $pid, *TO_CHLD_W, *FR_CHLD_R, *FR_CHLD_ERR_R );
1394 $cmd = [ grep { defined && length } @$cmd ] if ref $cmd;
1395 $cmd = $self->__fix_cmd_whitespace_and_special_chars( $cmd );
1397 my ($pid, $to_chld, $fr_chld, $fr_chld_err) =
1398 $open3->( ( ref $cmd ? @$cmd : $cmd ) );
1400 my $in_sel = IO::Select->new();
1401 my $out_sel = IO::Select->new();
1405 $objs{ fileno( $fr_chld ) } = $outhand;
1406 $objs{ fileno( $fr_chld_err ) } = $errhand;
1407 $in_sel->add( $fr_chld );
1408 $in_sel->add( $fr_chld_err );
1412 while ($in_sel->count() + $out_sel->count()) {
1413 my ($ins, $outs) = IO::Select::select($in_sel, $out_sel, undef);
1415 for my $fh (@$ins) {
1416 my $obj = $objs{ fileno($fh) };
1418 my $bytes_read = sysread($fh, $buf, 64*1024 ); #, length($buf));
1420 $in_sel->remove($fh);
1427 for my $fh (@$outs) {
1433 ### some error occurred
1435 $self->error( $self->_pp_child_error( $cmd, $? ) );
1439 return $self->ok( 1 );
1446 my $_out_handler = shift;
1447 my $_err_handler = shift;
1448 my $verbose = shift || 0;
1450 ### Following code are adapted from Friar 'abstracts' in the
1451 ### Perl Monastery (http://www.perlmonks.org/index.pl?node_id=151886).
1452 ### XXX that code didn't work.
1453 ### we now use the following code, thanks to theorbtwo
1455 ### define them beforehand, so we always have defined FH's
1458 my $kidout = Symbol::gensym();
1459 my $kiderror = Symbol::gensym();
1461 ### Dup the filehandle so we can pass 'our' STDIN to the
1462 ### child process. This stops us from having to pump input
1463 ### from ourselves to the childprocess. However, we will need
1464 ### to revive the FH afterwards, as IPC::Open3 closes it.
1465 ### We'll do the same for STDOUT and STDERR. It works without
1466 ### duping them on non-unix derivatives, but not on win32.
1467 my @fds_to_dup = ( IS_WIN32 && !$verbose
1468 ? qw[STDIN STDOUT STDERR]
1471 $self->_fds( \@fds_to_dup );
1472 $self->__dup_fds( @fds_to_dup );
1474 ### pipes have to come in a quoted string, and that clashes with
1475 ### whitespace. This sub fixes up such commands so they run properly
1476 $cmd = $self->__fix_cmd_whitespace_and_special_chars( $cmd );
1478 ### don't stringify @$cmd, so spaces in filenames/paths are
1479 ### treated properly
1483 (IS_WIN32 ? '>&STDOUT' : $kidout),
1484 (IS_WIN32 ? '>&STDERR' : $kiderror),
1485 ( ref $cmd ? @$cmd : $cmd ),
1489 ### open3 error occurred
1490 if( $@ and $@ =~ /^open3:/ ) {
1496 ### use OUR stdin, not $kidin. Somehow,
1497 ### we never get the input.. so jump through
1498 ### some hoops to do it :(
1499 my $selector = IO::Select->new(
1500 (IS_WIN32 ? \*STDERR : $kiderror),
1502 (IS_WIN32 ? \*STDOUT : $kidout)
1505 STDOUT->autoflush(1); STDERR->autoflush(1); STDIN->autoflush(1);
1506 $kidout->autoflush(1) if UNIVERSAL::can($kidout, 'autoflush');
1507 $kiderror->autoflush(1) if UNIVERSAL::can($kiderror, 'autoflush');
1509 ### add an explicit break statement
1510 ### code courtesy of theorbtwo from #london.pm
1511 my $stdout_done = 0;
1512 my $stderr_done = 0;
1513 OUTER: while ( my @ready = $selector->can_read ) {
1515 for my $h ( @ready ) {
1518 ### $len is the amount of bytes read
1519 my $len = sysread( $h, $buf, 4096 ); # try to read 4096 bytes
1521 ### see perldoc -f sysread: it returns undef on error,
1523 if( not defined $len ) {
1524 warn(loc("Error reading from process: %1", $!));
1528 ### check for $len. it may be 0, at which point we're
1529 ### done reading, so don't try to process it.
1530 ### if we would print anyway, we'd provide bogus information
1531 $_out_handler->( "$buf" ) if $len && $h == $kidout;
1532 $_err_handler->( "$buf" ) if $len && $h == $kiderror;
1534 ### Wait till child process is done printing to both
1535 ### stdout and stderr.
1536 $stdout_done = 1 if $h == $kidout and $len == 0;
1537 $stderr_done = 1 if $h == $kiderror and $len == 0;
1538 last OUTER if ($stdout_done && $stderr_done);
1542 waitpid $pid, 0; # wait for it to die
1544 ### restore STDIN after duping, or STDIN will be closed for
1545 ### this current perl process!
1546 ### done in the parent call now
1547 # $self->__reopen_fds( @fds_to_dup );
1549 ### some error occurred
1551 $self->error( $self->_pp_child_error( $cmd, $? ) );
1555 return $self->ok( 1 );
1559 ### Text::ParseWords::shellwords() uses unix semantics. that will break
1561 { my $parse_sub = IS_WIN32
1562 ? __PACKAGE__->can('_split_like_shell_win32')
1563 : Text::ParseWords->can('shellwords');
1568 my $_out_handler = shift;
1569 my $_err_handler = shift;
1571 STDOUT->autoflush(1); STDERR->autoflush(1);
1577 # '/Users/kane/sources/p4/other/archive-extract/t/src/x.tgz',
1582 ### needs to become:
1584 # ['/usr/bin/gzip', '-cdf',
1585 # '/Users/kane/sources/p4/other/archive-extract/t/src/x.tgz']
1587 # ['/usr/bin/tar', '-tf -']
1594 my $re = do { my $x = join '', SPECIAL_CHARS; qr/([$x])/ };
1597 for my $item (@$cmd) {
1598 if( $item =~ $re ) {
1599 push @command, $aref, $item;
1601 $special_chars .= $1;
1606 push @command, $aref;
1608 @command = map { if( $_ =~ $re ) {
1609 $special_chars .= $1; $_;
1612 [ map { m/[ ]/ ? qq{'$_'} : $_ } $parse_sub->($_) ]
1614 } split( /\s*$re\s*/, $cmd );
1617 ### if there's a pipe in the command, *STDIN needs to
1618 ### be inserted *BEFORE* the pipe, to work on win32
1619 ### this also works on *nix, so we should do it when possible
1620 ### this should *also* work on multiple pipes in the command
1621 ### if there's no pipe in the command, append STDIN to the back
1622 ### of the command instead.
1623 ### XXX seems IPC::Run works it out for itself if you just
1624 ### don't pass STDIN at all.
1625 # if( $special_chars and $special_chars =~ /\|/ ) {
1626 # ### only add STDIN the first time..
1628 # @command = map { ($_ eq '|' && not $i++)
1633 # push @command, \*STDIN;
1636 # \*STDIN is already included in the @command, see a few lines up
1637 my $ok = eval { IPC::Run::run( @command,
1647 return $self->ok( $ok );
1649 ### some error occurred
1653 ### if the eval fails due to an exception, deal with it
1654 ### unless it's an alarm
1655 if( $@ and not UNIVERSAL::isa( $@, ALARM_CLASS ) ) {
1658 ### if it *is* an alarm, propagate
1662 ### some error in the sub command
1664 $self->error( $self->_pp_child_error( $cmd, $? ) );
1675 my $verbose = shift || 0;
1677 ### pipes have to come in a quoted string, and that clashes with
1678 ### whitespace. This sub fixes up such commands so they run properly
1679 $cmd = $self->__fix_cmd_whitespace_and_special_chars( $cmd );
1681 my @fds_to_dup = $verbose ? () : qw[STDOUT STDERR];
1682 $self->_fds( \@fds_to_dup );
1683 $self->__dup_fds( @fds_to_dup );
1685 ### system returns 'true' on failure -- the exit code of the cmd
1687 system( ref $cmd ? @$cmd : $cmd ) == 0 or do {
1688 $self->error( $self->_pp_child_error( $cmd, $? ) );
1692 ### done in the parent call now
1693 #$self->__reopen_fds( @fds_to_dup );
1695 return unless $self->ok;
1699 { my %sc_lookup = map { $_ => $_ } SPECIAL_CHARS;
1702 sub __fix_cmd_whitespace_and_special_chars {
1706 ### command has a special char in it
1707 if( ref $cmd and grep { $sc_lookup{$_} } @$cmd ) {
1709 ### since we have special chars, we have to quote white space
1710 ### this *may* conflict with the parsing :(
1712 my @cmd = map { / / ? do { $fixed++; QUOTE.$_.QUOTE } : $_ } @$cmd;
1714 $self->_debug( "# Quoted $fixed arguments containing whitespace" )
1715 if $DEBUG && $fixed;
1717 ### stringify it, so the special char isn't escaped as argument
1719 $cmd = join ' ', @cmd;
1726 ### Command-line arguments (but not the command itself) must be quoted
1727 ### to ensure case preservation. Borrowed from Module::Build with adaptations.
1728 ### Patch for this supplied by Craig Berry, see RT #46288: [PATCH] Add argument
1729 ### quoting for run() on VMS
1730 sub _quote_args_vms {
1731 ### Returns a command string with proper quoting so that the subprocess
1732 ### sees this same list of args, or if we get a single arg that is an
1733 ### array reference, quote the elements of it (except for the first)
1734 ### and return the reference.
1736 my $got_arrayref = (scalar(@args) == 1
1737 && UNIVERSAL::isa($args[0], 'ARRAY'))
1741 @args = split(/\s+/, $args[0]) unless $got_arrayref || scalar(@args) > 1;
1743 my $cmd = $got_arrayref ? shift @{$args[0]} : shift @args;
1745 ### Do not quote qualifiers that begin with '/' or previously quoted args.
1746 map { if (/^[^\/\"]/) {
1747 $_ =~ s/\"/""/g; # escape C<"> by doubling
1751 ($got_arrayref ? @{$args[0]}
1755 $got_arrayref ? unshift(@{$args[0]}, $cmd) : unshift(@args, $cmd);
1757 return $got_arrayref ? $args[0]
1762 ### XXX this is cribbed STRAIGHT from M::B 0.30 here:
1763 ### http://search.cpan.org/src/KWILLIAMS/Module-Build-0.30/lib/Module/Build/Platform/Windows.pm:split_like_shell
1764 ### XXX this *should* be integrated into text::parsewords
1765 sub _split_like_shell_win32 {
1766 # As it turns out, Windows command-parsing is very different from
1767 # Unix command-parsing. Double-quotes mean different things,
1768 # backslashes don't necessarily mean escapes, and so on. So we
1769 # can't use Text::ParseWords::shellwords() to break a command string
1770 # into words. The algorithm below was bashed out by Randy and Ken
1771 # (mostly Randy), and there are a lot of regression tests, so we
1772 # should feel free to adjust if desired.
1777 return @argv unless defined() && length();
1780 my( $i, $quote_mode ) = ( 0, 0 );
1782 while ( $i < length() ) {
1784 my $ch = substr( $_, $i , 1 );
1785 my $next_ch = substr( $_, $i+1, 1 );
1787 if ( $ch eq '\\' && $next_ch eq '"' ) {
1790 } elsif ( $ch eq '\\' && $next_ch eq '\\' ) {
1793 } elsif ( $ch eq '"' && $next_ch eq '"' && $quote_mode ) {
1794 $quote_mode = !$quote_mode;
1797 } elsif ( $ch eq '"' && $next_ch eq '"' && !$quote_mode &&
1798 ( $i + 2 == length() ||
1799 substr( $_, $i + 2, 1 ) eq ' ' )
1800 ) { # for cases like: a"" => [ 'a' ]
1801 push( @argv, $arg );
1804 } elsif ( $ch eq '"' ) {
1805 $quote_mode = !$quote_mode;
1806 } elsif ( $ch eq ' ' && !$quote_mode ) {
1807 push( @argv, $arg ) if defined( $arg ) && length( $arg );
1809 ++$i while substr( $_, $i + 1, 1 ) eq ' ';
1817 push( @argv, $arg ) if defined( $arg ) && length( $arg );
1827 STDOUT => [qw|>&|, \*STDOUT, Symbol::gensym() ],
1828 STDERR => [qw|>&|, \*STDERR, Symbol::gensym() ],
1829 STDIN => [qw|<&|, \*STDIN, Symbol::gensym() ],
1832 ### dups FDs and stores them in a cache
1837 __PACKAGE__->_debug( "# Closing the following fds: @fds" ) if $DEBUG;
1839 for my $name ( @fds ) {
1840 my($redir, $fh, $glob) = @{$Map{$name}} or (
1841 Carp::carp(loc("No such FD: '%1'", $name)), next );
1843 ### MUST use the 2-arg version of open for dup'ing for
1844 ### 5.6.x compatibility. 5.8.x can use 3-arg open
1845 ### see perldoc5.6.2 -f open for details
1846 open $glob, $redir . fileno($fh) or (
1847 Carp::carp(loc("Could not dup '$name': %1", $!)),
1851 ### we should re-open this filehandle right now, not
1853 ### Use 2-arg version of open, as 5.5.x doesn't support
1854 ### 3-arg version =/
1855 if( $redir eq '>&' ) {
1856 open( $fh, '>' . File::Spec->devnull ) or (
1857 Carp::carp(loc("Could not reopen '$name': %1", $!)),
1866 ### reopens FDs from the cache
1871 __PACKAGE__->_debug( "# Reopening the following fds: @fds" ) if $DEBUG;
1873 for my $name ( @fds ) {
1874 my($redir, $fh, $glob) = @{$Map{$name}} or (
1875 Carp::carp(loc("No such FD: '%1'", $name)), next );
1877 ### MUST use the 2-arg version of open for dup'ing for
1878 ### 5.6.x compatibility. 5.8.x can use 3-arg open
1879 ### see perldoc5.6.2 -f open for details
1880 open( $fh, $redir . fileno($glob) ) or (
1881 Carp::carp(loc("Could not restore '$name': %1", $!)),
1885 ### close this FD, we're not using it anymore
1895 my $msg = shift or return;
1896 my $level = shift || 0;
1898 local $Carp::CarpLevel += $level;
1904 sub _pp_child_error {
1906 my $cmd = shift or return;
1907 my $ce = shift or return;
1908 my $pp_cmd = ref $cmd ? "@$cmd" : $cmd;
1913 ### Include $! in the error message, so that the user can
1914 ### see 'No such file or directory' versus 'Permission denied'
1915 ### versus 'Cannot fork' or whatever the cause was.
1916 $str = "Failed to execute '$pp_cmd': $!";
1918 } elsif ( $ce & 127 ) {
1920 $str = loc( "'%1' died with signal %2, %3 coredump",
1921 $pp_cmd, ($ce & 127), ($ce & 128) ? 'with' : 'without');
1924 ### Otherwise, the command run but gave error status.
1925 $str = "'$pp_cmd' exited with value " . ($ce >> 8);
1928 $self->_debug( "# Child error '$ce' translated to: $str" ) if $DEBUG;
1937 Returns the character used for quoting strings on this platform. This is
1938 usually a C<'> (single quote) on most systems, but some systems use different
1939 quotes. For example, C<Win32> uses C<"> (double quote).
1941 You can use it as follows:
1943 use IPC::Cmd qw[run QUOTE];
1944 my $cmd = q[echo ] . QUOTE . q[foo bar] . QUOTE;
1946 This makes sure that C<foo bar> is treated as a string, rather than two
1947 separate arguments to the C<echo> function.
1953 C<run> will try to execute your command using the following logic:
1959 If you have C<IPC::Run> installed, and the variable C<$IPC::Cmd::USE_IPC_RUN>
1960 is set to true (See the L<"Global Variables"> section) use that to execute
1961 the command. You will have the full output available in buffers, interactive commands
1962 are sure to work and you are guaranteed to have your verbosity
1963 settings honored cleanly.
1967 Otherwise, if the variable C<$IPC::Cmd::USE_IPC_OPEN3> is set to true
1968 (See the L<"Global Variables"> section), try to execute the command using
1969 L<IPC::Open3>. Buffers will be available on all platforms,
1970 interactive commands will still execute cleanly, and also your verbosity
1971 settings will be adhered to nicely;
1975 Otherwise, if you have the C<verbose> argument set to true, we fall back
1976 to a simple C<system()> call. We cannot capture any buffers, but
1977 interactive commands will still work.
1981 Otherwise we will try and temporarily redirect STDERR and STDOUT, do a
1982 C<system()> call with your command and then re-open STDERR and STDOUT.
1983 This is the method of last resort and will still allow you to execute
1984 your commands cleanly. However, no buffers will be available.
1988 =head1 Global Variables
1990 The behaviour of IPC::Cmd can be altered by changing the following
1993 =head2 $IPC::Cmd::VERBOSE
1995 This controls whether IPC::Cmd will print any output from the
1996 commands to the screen or not. The default is 0.
1998 =head2 $IPC::Cmd::USE_IPC_RUN
2000 This variable controls whether IPC::Cmd will try to use L<IPC::Run>
2001 when available and suitable.
2003 =head2 $IPC::Cmd::USE_IPC_OPEN3
2005 This variable controls whether IPC::Cmd will try to use L<IPC::Open3>
2006 when available and suitable. Defaults to true.
2008 =head2 $IPC::Cmd::WARN
2010 This variable controls whether run-time warnings should be issued, like
2011 the failure to load an C<IPC::*> module you explicitly requested.
2013 Defaults to true. Turn this off at your own risk.
2015 =head2 $IPC::Cmd::INSTANCES
2017 This variable controls whether C<can_run> will return all instances of
2018 the binary it finds in the C<PATH> when called in a list context.
2020 Defaults to false, set to true to enable the described behaviour.
2022 =head2 $IPC::Cmd::ALLOW_NULL_ARGS
2024 This variable controls whether C<run> will remove any empty/null arguments
2025 it finds in command arguments.
2027 Defaults to false, so it will remove null arguments. Set to true to allow
2034 =item Whitespace and IPC::Open3 / system()
2036 When using C<IPC::Open3> or C<system>, if you provide a string as the
2037 C<command> argument, it is assumed to be appropriately escaped. You can
2038 use the C<QUOTE> constant to use as a portable quote character (see above).
2039 However, if you provide an array reference, special rules apply:
2041 If your command contains B<special characters> (< > | &), it will
2042 be internally stringified before executing the command, to avoid that these
2043 special characters are escaped and passed as arguments instead of retaining
2044 their special meaning.
2046 However, if the command contained arguments that contained whitespace,
2047 stringifying the command would lose the significance of the whitespace.
2048 Therefore, C<IPC::Cmd> will quote any arguments containing whitespace in your
2049 command if the command is passed as an arrayref and contains special characters.
2051 =item Whitespace and IPC::Run
2053 When using C<IPC::Run>, if you provide a string as the C<command> argument,
2054 the string will be split on whitespace to determine the individual elements
2055 of your command. Although this will usually just Do What You Mean, it may
2056 break if you have files or commands with whitespace in them.
2058 If you do not wish this to happen, you should provide an array
2059 reference, where all parts of your command are already separated out.
2060 Note however, if there are extra or spurious whitespaces in these parts,
2061 the parser or underlying code may not interpret it correctly, and
2067 gzip -cdf foo.tar.gz | tar -xf -
2069 should either be passed as
2071 "gzip -cdf foo.tar.gz | tar -xf -"
2075 ['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']
2077 But take care not to pass it as, for example
2079 ['gzip -cdf foo.tar.gz', '|', 'tar -xf -']
2081 Since this will lead to issues as described above.
2086 Currently it is too complicated to parse your command for IO
2087 redirections. For capturing STDOUT or STDERR there is a work around
2088 however, since you can just inspect your buffers for the contents.
2090 =item Interleaving STDOUT/STDERR
2092 Neither IPC::Run nor IPC::Open3 can interleave STDOUT and STDERR. For short
2093 bursts of output from a program, e.g. this sample,
2096 $_ % 2 ? print STDOUT $_ : print STDERR $_;
2099 IPC::[Run|Open3] will first read all of STDOUT, then all of STDERR, meaning
2100 the output looks like '13' on STDOUT and '24' on STDERR, instead of
2107 This has been recorded in L<rt.cpan.org> as bug #37532: Unable to interleave
2114 L<IPC::Run>, L<IPC::Open3>
2116 =head1 ACKNOWLEDGEMENTS
2118 Thanks to James Mastros and Martijn van der Streek for their
2119 help in getting L<IPC::Open3> to behave nicely.
2121 Thanks to Petya Kohts for the C<run_forked> code.
2125 Please report bugs or other issues to E<lt>bug-ipc-cmd@rt.cpan.orgE<gt>.
2129 Original author: Jos Boumans E<lt>kane@cpan.orgE<gt>.
2130 Current maintainer: Chris Williams E<lt>bingos@cpan.orgE<gt>.
2134 This library is free software; you may redistribute and/or modify it
2135 under the same terms as Perl itself.