line
stmt
bran
cond
sub
pod
time
code
1
package IPC::Run;
2
231
231
8859733
use bytes;
231
84018
231
1032
3
4
=pod
5
6
=for markdown [](https://github.com/cpan-authors/IPC-Run/actions/workflows/testsuite.yml)
7
8
=head1 NAME
9
10
IPC::Run - system() and background procs w/ piping, redirs, ptys (Unix, Win32)
11
12
=head1 SYNOPSIS
13
14
## First,a command to run:
15
my @cat = qw( cat );
16
17
## Using run() instead of system():
18
use IPC::Run qw( run timeout );
19
20
run \@cat, \$in, \$out, \$err, timeout( 10 ) or die "cat: $?";
21
22
# Can do I/O to sub refs and filenames, too:
23
run \@cat, '<', "in.txt", \&out, \&err or die "cat: $?";
24
run \@cat, '<', "in.txt", '>>', "out.txt", '2>>', "err.txt";
25
26
27
# Redirecting using pseudo-terminals instead of pipes.
28
run \@cat, 'pty>', \$out_and_err;
29
30
## Scripting subprocesses (like Expect):
31
32
use IPC::Run qw( start pump finish timeout );
33
34
# Incrementally read from / write to scalars.
35
# $in is drained as it is fed to cat's stdin,
36
# $out accumulates cat's stdout
37
# $err accumulates cat's stderr
38
# $h is for "harness".
39
my $h = start \@cat, \$in, \$out, \$err, timeout( 10 );
40
41
$in .= "some input\n";
42
pump $h until $out =~ /input\n/g;
43
44
$in .= "some more input\n";
45
pump $h until $out =~ /\G.*more input\n/;
46
47
$in .= "some final input\n";
48
finish $h or die "cat returned $?";
49
50
warn $err if $err;
51
print $out; ## All of cat's output
52
53
# Piping between children
54
run \@cat, '|', \@gzip;
55
56
# Multiple children simultaneously (run() blocks until all
57
# children exit, use start() for background execution):
58
run \@foo1, '&', \@foo2;
59
60
# Calling \&set_up_child in the child before it executes the
61
# command (only works on systems with true fork() & exec())
62
# exceptions thrown in set_up_child() will be propagated back
63
# to the parent and thrown from run().
64
run \@cat, \$in, \$out,
65
init => \&set_up_child;
66
67
# Read from / write to file handles you open and close
68
open IN, '
69
open OUT, '>out.txt' or die $!;
70
print OUT "preamble\n";
71
run \@cat, \*IN, \*OUT or die "cat returned $?";
72
print OUT "postamble\n";
73
close IN;
74
close OUT;
75
76
# Create pipes for you to read / write (like IPC::Open2 & 3).
77
$h = start
78
\@cat,
79
'
80
'>pipe', \*OUT,
81
'2>pipe', \*ERR
82
or die "cat returned $?";
83
print IN "some input\n";
84
close IN;
85
print , ;
86
finish $h;
87
88
# Mixing input and output modes
89
run \@cat, 'in.txt', \&catch_some_out, \*ERR_LOG;
90
91
# Other redirection constructs
92
run \@cat, '>&', \$out_and_err;
93
run \@cat, '2>&1';
94
run \@cat, '0<&3';
95
run \@cat, '<&-';
96
run \@cat, '3<', \$in3;
97
run \@cat, '4>', \$out4;
98
# etc.
99
100
# Passing options:
101
run \@cat, 'in.txt', debug => 1;
102
103
# Call this system's shell, returns TRUE on 0 exit code
104
# THIS IS THE OPPOSITE SENSE OF system()'s RETURN VALUE
105
run "cat a b c" or die "cat returned $?";
106
107
# Launch a sub process directly, no shell. Can't do redirection
108
# with this form, it's here to behave like system() with an
109
# inverted result.
110
$r = run "cat a b c";
111
112
# Read from a file in to a scalar
113
run io( "filename", 'r', \$recv );
114
run io( \*HANDLE, 'r', \$recv );
115
116
=head1 DESCRIPTION
117
118
IPC::Run allows you to run and interact with child processes using files, pipes,
119
and pseudo-ttys. Both system()-style and scripted usages are supported and
120
may be mixed. Likewise, functional and OO API styles are both supported and
121
may be mixed.
122
123
Various redirection operators reminiscent of those seen on common Unix and DOS
124
command lines are provided.
125
126
=head1 SIMPLE QUICKSTART
127
128
Here's a quick guide to basic usage of using IPC::Run's C function.
129
130
=head2 Capturing output and errors from an external command
131
132
Say you want to run a command in your shell. We'll use C for
133
simplicity, although there are far better ways to get a list of files, such
134
as the C function or the L module.
135
136
The basic form of C has the command and its arguments passed as an
137
arrayref in the first argument. The command cannot be a single string.
138
139
@cmd = [ 'ls', '-a', '-l', '-r', '-t' ]; # Yes
140
@cmd = ( 'ls -a -l -r -t' ); # No
141
142
After the command, pass a scalar reference C<\$in> for the input to pass
143
in, and scalar references C<\$out> and C<\$err> to receive the content of
144
stdout and stderr.
145
146
use IPC::Run qw( run );
147
148
@cmd = qw( ls -l -a -r -t );
149
run( \@cmd, \$in, \$out, \$err ) or die $?;
150
151
print("\$err is ", length($err), " bytes long\n");
152
print($err, "\n");
153
154
print("\$out is ", length($out), " bytes long\n");
155
print($out, "\n");
156
157
Running this will show something like:
158
159
$err is 0 bytes long
160
161
$out is 1410 bytes long
162
total 392
163
drwxr-xr-x 3 andy staff 96 Mar 17 11:53 .github
164
-rw-r--r-- 1 andy staff 158 Mar 17 11:53 .gitignore
165
... etc ...
166
167
Note that C<$out> and C<$err> are always defined after a call to C,
168
even if they receive no data.
169
170
=head2 Passing input to the external program
171
172
If you have input to pass in, put it in the C<$in> variables. For example,
173
to use the C command to count lines, words and characters in a block of
174
text:
175
176
$in = <<'CARROLL';
177
'Twas brillig, and the slithy toves
178
Did gyre and gimble in the wabe:
179
All mimsy were the borogoves,
180
And the mome raths outgrabe.
181
CARROLL
182
183
@cmd = qw( wc );
184
run( \@cmd, \$in, \$out, \$err ) or die $?;
185
print "$out";
186
187
This gives the output:
188
189
4 23 140
190
191
=head2 Handling errors
192
193
It's important to check the return code of C to see if the command
194
ran successfully. C returns a boolean true on success, and false on
195
failure. Note that this is the opposite of Perl's C, which
196
returns 0 on success and a non-zero value on failures.
197
198
For the specific subprocess error code, check C<$?> directly.
199
200
@cmd = qw( tar xzvf nonexistent.tar );
201
if ( !run( \@cmd, \$in, \$out, \$err ) ) {
202
print "\$? = $?\n";
203
print "err = $err\n";
204
}
205
206
Running this gives:
207
208
$? = 256
209
err = tar: Error opening archive: Failed to open 'nonexistent.tar'
210
211
If the program does not exist, then C will C and won't return
212
at all. For example:
213
214
@cmd = qw( bogus-command );
215
my $rc = run( \@cmd, \$in, \$out, \$err );
216
print "run returned ", ($rc ? "true" : "false"), "\n";
217
218
Running this doesn't make it to the C statement.
219
220
Command 'bogus-command' not found in [ list of paths ] at program.pl line N.
221
222
To handle the possibility of a non-existent program, call C inside
223
an C.
224
225
my $rc;
226
eval { $rc = run( \@cmd, \$in, \$out, \$out ); 1; };
227
if ( !defined($rc) ) {
228
print "run died: $@\n";
229
}
230
else {
231
if ( $rc ) {
232
print "run returned true\n";
233
}
234
else {
235
print "run returned false\n";
236
print "\$? = $?\n";
237
}
238
}
239
240
=head2 And beyond
241
242
That's the basics of using C as a replacement for C. If you'd
243
like to do more, such as having subprocesses communicate with each other,
244
setting timeouts on long-running processes, kill running subprocesses,
245
redirecting output, closing file descriptors and much much MUCH more, read on.
246
247
=head1 THE DETAILS
248
249
Before digging in to the details a few LIMITATIONS are important enough
250
to be mentioned right up front:
251
252
=over
253
254
=item Win32 Support
255
256
Win32 support is working but B, but does pass all relevant tests
257
on NT 4.0. See L.
258
259
=item pty Support
260
261
If you need pty support, IPC::Run should work well enough most of the
262
time, but IO::Pty is being improved, and IPC::Run will be improved to
263
use IO::Pty's new features when it is released.
264
265
The basic problem is that the pty needs to initialize itself before the
266
parent writes to the master pty, or the data written gets lost. So
267
IPC::Run does a sleep(1) in the parent after forking to (hopefully) give
268
the child a chance to run. This is a kludge that works well on non
269
heavily loaded systems :(.
270
271
ptys are not supported yet under Win32, but will be emulated...
272
273
=item Debugging Tip
274
275
You may use the environment variable C to see what's going on
276
under the hood:
277
278
$ IPCRUNDEBUG=basic myscript # prints minimal debugging
279
$ IPCRUNDEBUG=data myscript # prints all data reads/writes
280
$ IPCRUNDEBUG=details myscript # prints lots of low-level details
281
$ IPCRUNDEBUG=gory myscript # (Win32 only) prints data moving through
282
# the helper processes.
283
284
=back
285
286
=head2 Harnesses
287
288
Child processes and I/O handles are gathered in to a harness, then
289
started and run until the processing is finished or aborted.
290
291
=head2 run() vs. start(); pump(); finish();
292
293
There are two modes you can run harnesses in: run() functions as an
294
enhanced system(), and start()/pump()/finish() allow for background
295
processes and scripted interactions with them.
296
297
When using run(), all data to be sent to the harness is set up in
298
advance (though one can feed subprocesses input from subroutine refs to
299
get around this limitation). The harness is run and all output is
300
collected from it, then any child processes are waited for:
301
302
run \@cmd, \<
303
blah
304
IN
305
306
## To precompile harnesses and run them later:
307
my $h = harness \@cmd, \<
308
blah
309
IN
310
311
run $h;
312
313
The background and scripting API is provided by start(), pump(), and
314
finish(): start() creates a harness if need be (by calling harness())
315
and launches any subprocesses, pump() allows you to poll them for
316
activity, and finish() then monitors the harnessed activities until they
317
complete.
318
319
## Build the harness, open all pipes, and launch the subprocesses
320
my $h = start \@cat, \$in, \$out;
321
$in = "first input\n";
322
323
## Now do I/O. start() does no I/O.
324
pump $h while length $in; ## Wait for all input to go
325
326
## Now do some more I/O.
327
$in = "second input\n";
328
pump $h until $out =~ /second input/;
329
330
## Clean up
331
finish $h or die "cat returned $?";
332
333
You can optionally compile the harness with harness() prior to
334
start()ing or run()ing, and you may omit start() between harness() and
335
pump(). You might want to do these things if you compile your harnesses
336
ahead of time.
337
338
=head2 Using regexps to match output
339
340
As shown in most of the scripting examples, the read-to-scalar facility
341
for gathering subcommand's output is often used with regular expressions
342
to detect stopping points. This is because subcommand output often
343
arrives in dribbles and drabs, often only a character or line at a time.
344
This output is input for the main program and piles up in variables like
345
the C<$out> and C<$err> in our examples.
346
347
Regular expressions can be used to wait for appropriate output in
348
several ways. The C example in the previous section demonstrates
349
how to pump() until some string appears in the output. Here's an
350
example that uses C to fetch files from a remote server:
351
352
$h = harness \@smbclient, \$in, \$out;
353
354
$in = "cd /src\n";
355
$h->pump until $out =~ /^smb.*> \Z/m;
356
die "error cding to /src:\n$out" if $out =~ "ERR";
357
$out = '';
358
359
$in = "mget *\n";
360
$h->pump until $out =~ /^smb.*> \Z/m;
361
die "error retrieving files:\n$out" if $out =~ "ERR";
362
363
$in = "quit\n";
364
$h->finish;
365
366
Notice that we carefully clear $out after the first command/response
367
cycle? That's because IPC::Run does not delete $out when we continue,
368
and we don't want to trip over the old output in the second
369
command/response cycle.
370
371
Say you want to accumulate all the output in $out and analyze it
372
afterwards. Perl offers incremental regular expression matching using
373
the C and pattern matching idiom and the C<\G> assertion.
374
IPC::Run is careful not to disturb the current C value for
375
scalars it appends data to, so we could modify the above so as not to
376
destroy $out by adding a couple of C modifiers. The C keeps us
377
from tripping over the previous prompt and the C keeps us from
378
resetting the prior match position if the expected prompt doesn't
379
materialize immediately:
380
381
$h = harness \@smbclient, \$in, \$out;
382
383
$in = "cd /src\n";
384
$h->pump until $out =~ /^smb.*> \Z/mgc;
385
die "error cding to /src:\n$out" if $out =~ "ERR";
386
387
$in = "mget *\n";
388
$h->pump until $out =~ /^smb.*> \Z/mgc;
389
die "error retrieving files:\n$out" if $out =~ "ERR";
390
391
$in = "quit\n";
392
$h->finish;
393
394
analyze( $out );
395
396
When using this technique, you may want to preallocate $out to have
397
plenty of memory or you may find that the act of growing $out each time
398
new input arrives causes an C slowdown as $out grows.
399
Say we expect no more than 10,000 characters of input at the most. To
400
preallocate memory to $out, do something like:
401
402
my $out = "x" x 10_000;
403
$out = "";
404
405
C will allocate at least 10,000 characters' worth of space, then
406
mark the $out as having 0 length without freeing all that yummy RAM.
407
408
=head2 Timeouts and Timers
409
410
More than likely, you don't want your subprocesses to run forever, and
411
sometimes it's nice to know that they're going a little slowly.
412
Timeouts throw exceptions after a some time has elapsed, timers merely
413
cause pump() to return after some time has elapsed. Neither is
414
reset/restarted automatically.
415
416
Timeout objects are created by calling timeout( $interval ) and passing
417
the result to run(), start() or harness(). The timeout period starts
418
ticking just after all the child processes have been fork()ed or
419
spawn()ed, and are polled for expiration in run(), pump() and finish().
420
If/when they expire, an exception is thrown. This is typically useful
421
to keep a subprocess from taking too long.
422
423
If a timeout occurs in run(), all child processes will be terminated and
424
all file/pipe/ptty descriptors opened by run() will be closed. File
425
descriptors opened by the parent process and passed in to run() are not
426
closed in this event.
427
428
If a timeout occurs in pump(), pump_nb(), or finish(), it's up to you to
429
decide whether to kill_kill() all the children or to implement some more
430
graceful fallback. No I/O will be closed in pump(), pump_nb() or
431
finish() by such an exception (though I/O is often closed down in those
432
routines during the natural course of events).
433
434
Often an exception is too harsh. timer( $interval ) creates timer
435
objects that merely prevent pump() from blocking forever. This can be
436
useful for detecting stalled I/O or printing a soothing message or "."
437
to pacify an anxious user.
438
439
Timeouts and timers can both be restarted at any time using the timer's
440
start() method (this is not the start() that launches subprocesses). To
441
restart a timer, you need to keep a reference to the timer:
442
443
## Start with a nice long timeout to let smbclient connect. If
444
## pump or finish take too long, an exception will be thrown.
445
446
my $h;
447
eval {
448
$h = harness \@smbclient, \$in, \$out, \$err, ( my $t = timeout 30 );
449
sleep 11; # No effect: timer not running yet
450
451
start $h;
452
$in = "cd /src\n";
453
pump $h until ! length $in;
454
455
$in = "ls\n";
456
## Now use a short timeout, since this should be faster
457
$t->start( 5 );
458
pump $h until ! length $in;
459
460
$t->start( 10 ); ## Give smbclient a little while to shut down.
461
$h->finish;
462
};
463
if ( $@ ) {
464
my $x = $@; ## Preserve $@ in case another exception occurs
465
$h->kill_kill; ## kill it gently, then brutally if need be, or just
466
## brutally on Win32.
467
die $x;
468
}
469
470
Timeouts and timers are I checked once the subprocesses are shut
471
down; they will not expire in the interval between the last valid
472
process and when IPC::Run scoops up the processes' result codes, for
473
instance.
474
475
=head2 Spawning synchronization, child exception propagation
476
477
start() pauses the parent until the child executes the command or CODE
478
reference and propagates any exceptions thrown (including exec()
479
failure) back to the parent. This has several pleasant effects: any
480
exceptions thrown in the child, including exec() failure, come flying
481
out of start() or run() as though they had occurred in the parent.
482
483
This includes exceptions your code thrown from init subs. In this
484
example:
485
486
eval {
487
run \@cmd, init => sub { die "blast it! foiled again!" };
488
};
489
print $@;
490
491
the exception "blast it! foiled again" will be thrown from the child
492
process (preventing the exec()) and printed by the parent.
493
494
In situations like
495
496
run \@cmd1, "|", \@cmd2, "|", \@cmd3;
497
498
@cmd1 will be initted and exec()ed before @cmd2, and @cmd2 before @cmd3.
499
This can save time and prevent oddball errors emitted by later commands
500
when earlier commands fail to execute. Note that IPC::Run doesn't start
501
any commands unless it can find the executables referenced by all
502
commands. These executables must pass both the C<-f> and C<-x> tests
503
described in L.
504
505
Another nice effect is that init() subs can take their time doing things
506
and there will be no problems caused by a parent continuing to execute
507
before a child's init() routine is complete. Say the init() routine
508
needs to open a socket or a temp file that the parent wants to connect
509
to; without this synchronization, the parent will need to implement a
510
retry loop to wait for the child to run, since often, the parent gets a
511
lot of things done before the child's first timeslice is allocated.
512
513
This is also quite necessary for pseudo-tty initialization, which needs
514
to take place before the parent writes to the child via pty. Writes
515
that occur before the pty is set up can get lost.
516
517
A final, minor, nicety is that debugging output from the child will be
518
emitted before the parent continues on, making for much clearer debugging
519
output in complex situations.
520
521
The only drawback I can conceive of is that the parent can't continue to
522
operate while the child is being initted. If this ever becomes a
523
problem in the field, we can implement an option to avoid this behavior,
524
but I don't expect it to.
525
526
B: executing CODE references isn't supported on Win32, see
527
L for details.
528
529
=head2 Syntax
530
531
run(), start(), and harness() can all take a harness specification
532
as input. A harness specification is either a single string to be passed
533
to the systems' shell:
534
535
run "echo 'hi there'";
536
537
or a list of commands, io operations, and/or timers/timeouts to execute.
538
Consecutive commands must be separated by a pipe operator '|' or an '&'.
539
External commands are passed in as array references or L
540
objects. On systems supporting fork(), Perl code may be passed in as subs:
541
542
run \@cmd;
543
run \@cmd1, '|', \@cmd2;
544
run \@cmd1, '&', \@cmd2;
545
run \&sub1;
546
run \&sub1, '|', \&sub2;
547
run \&sub1, '&', \&sub2;
548
549
'|' pipes the stdout of \@cmd1 the stdin of \@cmd2, just like a
550
shell pipe. '&' does not. Child processes to the right of a '&'
551
will have their stdin closed unless it's redirected-to.
552
553
L objects may be passed in as well, whether or not
554
child processes are also specified:
555
556
run io( "infile", ">", \$in ), io( "outfile", "<", \$in );
557
558
as can L objects:
559
560
run \@cmd, io( "outfile", "<", \$in ), timeout( 10 );
561
562
Commands may be followed by scalar, sub, or i/o handle references for
563
redirecting
564
child process input & output:
565
566
run \@cmd, \undef, \$out;
567
run \@cmd, \$in, \$out;
568
run \@cmd1, \&in, '|', \@cmd2, \*OUT;
569
run \@cmd1, \*IN, '|', \@cmd2, \&out;
570
571
This is known as succinct redirection syntax, since run(), start()
572
and harness(), figure out which file descriptor to redirect and how.
573
File descriptor 0 is presumed to be an input for
574
the child process, all others are outputs. The assumed file
575
descriptor always starts at 0, unless the command is being piped to,
576
in which case it starts at 1.
577
578
To be explicit about your redirects, or if you need to do more complex
579
things, there's also a redirection operator syntax:
580
581
run \@cmd, '<', \undef, '>', \$out;
582
run \@cmd, '<', \undef, '>&', \$out_and_err;
583
run(
584
\@cmd1,
585
'<', \$in,
586
'|', \@cmd2,
587
\$out
588
);
589
590
Operator syntax is required if you need to do something other than simple
591
redirection to/from scalars or subs, like duping or closing file descriptors
592
or redirecting to/from a named file. The operators are covered in detail
593
below.
594
595
After each \@cmd (or \&foo), parsing begins in succinct mode and toggles to
596
operator syntax mode when an operator (ie plain scalar, not a ref) is seen.
597
Once in
598
operator syntax mode, parsing only reverts to succinct mode when a '|' or
599
'&' is seen.
600
601
In succinct mode, each parameter after the \@cmd specifies what to
602
do with the next highest file descriptor. These File descriptor start
603
with 0 (stdin) unless stdin is being piped to (C<'|', \@cmd>), in which
604
case they start with 1 (stdout). Currently, being on the left of
605
a pipe (C<\@cmd, \$out, \$err, '|'>) does I cause stdout to be
606
skipped, though this may change since it's not as DWIMerly as it
607
could be. Only stdin is assumed to be an
608
input in succinct mode, all others are assumed to be outputs.
609
610
If no piping or redirection is specified for a child, it will inherit
611
the parent's open file handles as dictated by your system's
612
close-on-exec behavior and the $^F flag, except that processes after a
613
'&' will not inherit the parent's stdin. Also note that $^F does not
614
affect file descriptors obtained via POSIX, since it only applies to
615
full-fledged Perl file handles. Such processes will have their stdin
616
closed unless it has been redirected-to.
617
618
If you want to close a child processes stdin, you may do any of:
619
620
run \@cmd, \undef;
621
run \@cmd, \"";
622
run \@cmd, '<&-';
623
run \@cmd, '0<&-';
624
625
Redirection is done by placing redirection specifications immediately
626
after a command or child subroutine:
627
628
run \@cmd1, \$in, '|', \@cmd2, \$out;
629
run \@cmd1, '<', \$in, '|', \@cmd2, '>', \$out;
630
631
If you omit the redirection operators, descriptors are counted
632
starting at 0. Descriptor 0 is assumed to be input, all others
633
are outputs. A leading '|' consumes descriptor 0, so this
634
works as expected.
635
636
run \@cmd1, \$in, '|', \@cmd2, \$out;
637
638
The parameter following a redirection operator can be a scalar ref,
639
a subroutine ref, a file name, an open filehandle, or a closed
640
filehandle.
641
642
If it's a scalar ref, the child reads input from or sends output to
643
that variable:
644
645
$in = "Hello World.\n";
646
run \@cat, \$in, \$out;
647
print $out;
648
649
Scalars used in incremental (start()/pump()/finish()) applications are treated
650
as queues: input is removed from input scalars, resulting in them dwindling
651
to '', and output is appended to output scalars. This is not true of
652
harnesses run() in batch mode.
653
654
It's usually wise to append new input to be sent to the child to the input
655
queue, and you'll often want to zap output queues to '' before pumping.
656
657
$h = start \@cat, \$in;
658
$in = "line 1\n";
659
pump $h;
660
$in .= "line 2\n";
661
pump $h;
662
$in .= "line 3\n";
663
finish $h;
664
665
The final call to finish() must be there: it allows the child process(es)
666
to run to completion and waits for their exit values.
667
668
=head1 OBSTINATE CHILDREN
669
670
Interactive applications are usually optimized for human use. This
671
can help or hinder trying to interact with them through modules like
672
IPC::Run. Frequently, programs alter their behavior when they detect
673
that stdin, stdout, or stderr are not connected to a tty, assuming that
674
they are being run in batch mode. Whether this helps or hurts depends
675
on which optimizations change. And there's often no way of telling
676
what a program does in these areas other than trial and error and
677
occasionally, reading the source. This includes different versions
678
and implementations of the same program.
679
680
All hope is not lost, however. Most programs behave in reasonably
681
tractable manners, once you figure out what it's trying to do.
682
683
Here are some of the issues you might need to be aware of.
684
685
=over
686
687
=item *
688
689
fflush()ing stdout and stderr
690
691
This lets the user see stdout and stderr immediately. Many programs
692
undo this optimization if stdout is not a tty, making them harder to
693
manage by things like IPC::Run.
694
695
Many programs decline to fflush stdout or stderr if they do not
696
detect a tty there. Some ftp commands do this, for instance.
697
698
If this happens to you, look for a way to force interactive behavior,
699
like a command line switch or command. If you can't, you will
700
need to use a pseudo terminal ('pty>').
701
702
=item *
703
704
false prompts
705
706
Interactive programs generally do not guarantee that output from user
707
commands won't contain a prompt string. For example, your shell prompt
708
might be a '$', and a file named '$' might be the only file in a directory
709
listing.
710
711
This can make it hard to guarantee that your output parser won't be fooled
712
into early termination of results.
713
714
To help work around this, you can see if the program can alter its
715
prompt, and use something you feel is never going to occur in actual
716
practice.
717
718
You should also look for your prompt to be the only thing on a line:
719
720
pump $h until $out =~ /^\s?\z/m;
721
722
(use C<(?!\n)\Z> in place of C<\z> on older perls).
723
724
You can also take the approach that IPC::ChildSafe takes and emit a
725
command with known output after each 'real' command you issue, then
726
look for this known output. See new_appender() and new_chunker() for
727
filters that can help with this task.
728
729
If it's not convenient or possibly to alter a prompt or use a known
730
command/response pair, you might need to autodetect the prompt in case
731
the local version of the child program is different then the one
732
you tested with, or if the user has control over the look & feel of
733
the prompt.
734
735
=item *
736
737
Refusing to accept input unless stdin is a tty.
738
739
Some programs, for security reasons, will only accept certain types
740
of input from a tty. su, notable, will not prompt for a password unless
741
it's connected to a tty.
742
743
If this is your situation, use a pseudo terminal ('pty>').
744
745
=item *
746
747
Not prompting unless connected to a tty.
748
749
Some programs don't prompt unless stdin or stdout is a tty. See if you can
750
turn prompting back on. If not, see if you can come up with a command that
751
you can issue after every real command and look for its output, as
752
IPC::ChildSafe does. There are two filters included with IPC::Run that
753
can help with doing this: appender and chunker (see new_appender() and
754
new_chunker()).
755
756
=item *
757
758
Different output format when not connected to a tty.
759
760
Some commands alter their formats to ease machine parsability when they
761
aren't connected to a pipe. This is actually good, but can be surprising.
762
763
=back
764
765
=head1 PSEUDO TERMINALS
766
767
On systems providing pseudo terminals under /dev, IPC::Run can use IO::Pty
768
(available on CPAN) to provide a terminal environment to subprocesses.
769
This is necessary when the subprocess really wants to think it's connected
770
to a real terminal.
771
772
=head2 CAVEATS
773
774
Pseudo-terminals are not pipes, though they are similar. Here are some
775
differences to watch out for.
776
777
=over
778
779
=item Echoing
780
781
Sending to stdin will cause an echo on stdout, which occurs before each
782
line is passed to the child program. There is currently no way to
783
disable this, although the child process can and should disable it for
784
things like passwords.
785
786
=item Shutdown
787
788
IPC::Run cannot close a pty until all output has been collected. This
789
means that it is not possible to send an EOF to stdin by half-closing
790
the pty, as we can when using a pipe to stdin.
791
792
This means that you need to send the child process an exit command or
793
signal, or run() / finish() will time out. Be careful not to expect a
794
prompt after sending the exit command.
795
796
=item Command line editing
797
798
Some subprocesses, notable shells that depend on the user's prompt
799
settings, will reissue the prompt plus the command line input so far
800
once for each character.
801
802
=item '>pty>' means '&>pty>', not '1>pty>'
803
804
The pseudo terminal redirects both stdout and stderr unless you specify
805
a file descriptor. If you want to grab stderr separately, do this:
806
807
start \@cmd, 'pty>', \$out, '2>', \$err;
808
809
=item stdin, stdout, and stderr not inherited
810
811
Child processes harnessed to a pseudo terminal have their stdin, stdout,
812
and stderr completely closed before any redirection operators take
813
effect. This casts off the bonds of the controlling terminal. This is
814
not done when using pipes.
815
816
Right now, this affects all children in a harness that has a pty in use,
817
even if that pty would not affect a particular child. That's a bug and
818
will be fixed. Until it is, it's best not to mix-and-match children.
819
820
=back
821
822
=head2 Redirection Operators
823
824
Operator SHNP Description
825
======== ==== ===========
826
<, N< SHN Redirects input to a child's fd N (0 assumed)
827
828
>, N> SHN Redirects output from a child's fd N (1 assumed)
829
>>, N>> SHN Like '>', but appends to scalars or named files
830
>&, &> SHN Redirects stdout & stderr from a child process
831
832
833
>pty, N>pty S Like '>', but uses a pseudo-tty instead of a pipe
834
835
N<&M Dups input fd N to input fd M
836
M>&N Dups output fd N to input fd M
837
N<&- Closes fd N
838
839
840
841
N
842
>pipe, N>pipe P Pipe opens H for caller to read, write, close.
843
844
'N' and 'M' are placeholders for integer file descriptor numbers. The
845
terms 'input' and 'output' are from the child process's perspective.
846
847
The SHNP field indicates what parameters an operator can take:
848
849
S: \$scalar or \&function references. Filters may be used with
850
these operators (and only these).
851
H: \*HANDLE or IO::Handle for caller to open, and close
852
N: "file name".
853
P: \*HANDLE or lexical filehandle opened by IPC::Run as the parent end of a pipe, but read
854
and written to and closed by the caller (like IPC::Open3).
855
856
=over
857
858
=item Redirecting input: [n]<, [n]
859
860
You can input the child reads on file descriptor number n to come from a
861
scalar variable, subroutine, file handle, or a named file. If stdin
862
is not redirected, the parent's stdin is inherited.
863
864
run \@cat, \undef ## Closes child's stdin immediately
865
or die "cat returned $?";
866
867
run \@cat, \$in;
868
869
run \@cat, \<
870
blah
871
TOHERE
872
873
run \@cat, \&input; ## Calls &input, feeding data returned
874
## to child's. Closes child's stdin
875
## when undef is returned.
876
877
Redirecting from named files requires you to use the input
878
redirection operator:
879
880
run \@cat, '<.profile';
881
run \@cat, '<', '.profile';
882
883
open IN, "
884
run \@cat, \*IN;
885
run \@cat, *IN{IO};
886
887
The form used second example here is the safest,
888
since filenames like "0" and "&more\n" won't confuse &run:
889
890
You can't do either of
891
892
run \@a, *IN; ## INVALID
893
run \@a, '<', *IN; ## BUGGY: Reads file named like "*main::A"
894
895
because perl passes a scalar containing a string that
896
looks like "*main::A" to &run, and &run can't tell the difference
897
between that and a redirection operator or a file name. &run guarantees
898
that any scalar you pass after a redirection operator is a file name.
899
900
If your child process will take input from file descriptors other
901
than 0 (stdin), you can use a redirection operator with any of the
902
valid input forms (scalar ref, sub ref, etc.):
903
904
run \@cat, '3<', \$in3;
905
906
When redirecting input from a scalar ref, the scalar ref is
907
used as a queue. This allows you to use &harness and pump() to
908
feed incremental bits of input to a coprocess. See L and
909
L for more information.
910
911
The
912
glob reference it takes as an argument:
913
914
$h = start \@cat, '
915
print IN "hello world\n";
916
close IN;
917
pump $h;
918
finish $h;
919
920
B: The pipe must be closed before calling pump() for commands
921
that buffer their output until stdin is closed (e.g. C). For
922
interactive commands that produce output in response to each line of
923
input, you may interleave writes and pump() calls without closing
924
first.
925
926
Unlike the other '<' operators, IPC::Run does nothing further with
927
it: you are responsible for it. The previous example is functionally
928
equivalent to:
929
930
pipe( \*R, \*IN ) or die $!;
931
$h = start \@cat, '<', \*R;
932
print IN "hello world\n";
933
close IN;
934
pump $h;
935
finish $h;
936
937
This is like the behavior of IPC::Open2 and IPC::Open3.
938
939
B: The write end of the pipe opened by C<< > is set to
940
B mode. This allows IPC::Run to fill the pipe buffer and
941
continue to its select() loop without stalling. However, if you write a
942
large amount of data faster than the child process reads it, you may receive
943
C / C errors from print(). If you need blocking writes
944
(for example, when acting as the start of a pipeline where you want to write
945
at the child's pace), use C<< > instead:
946
947
$h = start \@wc, '
948
print IN "lots of data\n" x 32768; ## won't get EAGAIN
949
close IN;
950
$h->finish;
951
952
C<< > behaves identically to C<< >, but does not set
953
the write end to non-blocking mode.
954
955
B: The handle returned is actually a socket handle, so you can
956
use select() on it.
957
958
=item Redirecting output: [n]>, [n]>>, [n]>&[m], [n]>pipe
959
960
You can redirect any output the child emits
961
to a scalar variable, subroutine, file handle, or file name. You
962
can have &run truncate or append to named files or scalars. If
963
you are redirecting stdin as well, or if the command is on the
964
receiving end of a pipeline ('|'), you can omit the redirection
965
operator:
966
967
@ls = ( 'ls' );
968
run \@ls, \undef, \$out
969
or die "ls returned $?";
970
971
run \@ls, \undef, \&out; ## Calls &out each time some output
972
## is received from the child's
973
## when undef is returned.
974
975
run \@ls, \undef, '2>ls.err';
976
run \@ls, '2>', 'ls.err';
977
978
The two parameter form guarantees that the filename
979
will not be interpreted as a redirection operator:
980
981
run \@ls, '>', "&more";
982
run \@ls, '2>', ">foo\n";
983
984
You can pass file handles you've opened for writing:
985
986
open( *OUT, ">out.txt" );
987
open( *ERR, ">err.txt" );
988
run \@cat, \*OUT, \*ERR;
989
990
Passing a scalar reference and a code reference requires a little
991
more work, but allows you to capture all of the output in a scalar
992
or each piece of output by a callback:
993
994
These two do the same things:
995
996
run( [ 'ls' ], '2>', sub { $err_out .= $_[0] } );
997
998
does the same basic thing as:
999
1000
run( [ 'ls' ], '2>', \$err_out );
1001
1002
The subroutine will be called each time some data is read from the child.
1003
1004
The >pipe operator is different in concept than the other '>' operators,
1005
although its syntax is similar:
1006
1007
$h = start \@cat, $in, '>pipe', \*OUT, '2>pipe', \*ERR;
1008
$in = "hello world\n";
1009
finish $h;
1010
print ;
1011
print ;
1012
close OUT;
1013
close ERR;
1014
1015
causes two pipe to be created, with one end attached to cat's stdout
1016
and stderr, respectively, and the other left open on OUT and ERR, so
1017
that the script can manually
1018
read(), select(), etc. on them. This is like
1019
the behavior of IPC::Open2 and IPC::Open3.
1020
1021
B: The handle returned is actually a socket handle, so you can
1022
use select() on it.
1023
1024
=item Duplicating output descriptors: >&m, n>&m
1025
1026
This duplicates output descriptor number n (default is 1 if n is omitted)
1027
from descriptor number m.
1028
1029
=item Duplicating input descriptors: <&m, n<&m
1030
1031
This duplicates input descriptor number n (default is 0 if n is omitted)
1032
from descriptor number m
1033
1034
=item Closing descriptors: <&-, 3<&-
1035
1036
This closes descriptor number n (default is 0 if n is omitted). The
1037
following commands are equivalent:
1038
1039
run \@cmd, \undef;
1040
run \@cmd, '<&-';
1041
run \@cmd, '
1042
1043
Doing
1044
1045
run \@cmd, \$in, '<&-'; ## SIGPIPE recipe.
1046
1047
is dangerous: the parent will get a SIGPIPE if $in is not empty.
1048
1049
=item Redirecting both stdout and stderr: &>, >&, &>pipe, >pipe&
1050
1051
The following pairs of commands are equivalent:
1052
1053
run \@cmd, '>&', \$out; run \@cmd, '>', \$out, '2>&1';
1054
run \@cmd, '>&', 'out.txt'; run \@cmd, '>', 'out.txt', '2>&1';
1055
1056
etc.
1057
1058
File descriptor numbers are not permitted to the left or the right of
1059
these operators, and the '&' may occur on either end of the operator.
1060
1061
The '&>pipe' and '>pipe&' variants behave like the '>pipe' operator, except
1062
that both stdout and stderr write to the created pipe.
1063
1064
=item Redirection Filters
1065
1066
Both input redirections and output redirections that use scalars or
1067
subs as endpoints may have an arbitrary number of filter subs placed
1068
between them and the child process. This is useful if you want to
1069
receive output in chunks, or if you want to massage each chunk of
1070
data sent to the child. To use this feature, you must use operator
1071
syntax:
1072
1073
run(
1074
\@cmd
1075
'<', \&in_filter_2, \&in_filter_1, $in,
1076
'>', \&out_filter_1, \&in_filter_2, $out,
1077
);
1078
1079
This capability is not provided for IO handles or named files.
1080
1081
Two filters are provided by IPC::Run: appender and chunker. Because
1082
these may take an argument, you need to use the constructor functions
1083
new_appender() and new_chunker() rather than using \& syntax:
1084
1085
run(
1086
\@cmd
1087
'<', new_appender( "\n" ), $in,
1088
'>', new_chunker, $out,
1089
);
1090
1091
=back
1092
1093
=head2 Just doing I/O
1094
1095
If you just want to do I/O to a handle or file you open yourself, you
1096
may specify a filehandle or filename instead of a command in the harness
1097
specification:
1098
1099
run io( "filename", '>', \$recv );
1100
1101
$h = start io( $io, '>', \$recv );
1102
1103
$h = harness \@cmd, '&', io( "file", '<', \$send );
1104
1105
=head2 Options
1106
1107
Options are passed in as name/value pairs:
1108
1109
run \@cat, \$in, debug => 1;
1110
1111
If you pass the debug option, you may want to pass it in first, so you
1112
can see what parsing is going on:
1113
1114
run debug => 1, \@cat, \$in;
1115
1116
=over
1117
1118
=item debug
1119
1120
Enables debugging output in parent and child. Debugging info is emitted
1121
to the STDERR that was present when IPC::Run was first Ced (it's
1122
Ced out of the way so that it can be redirected in children without
1123
having debugging output emitted on it).
1124
1125
=back
1126
1127
=head1 RETURN VALUES
1128
1129
harness() and start() return a reference to an IPC::Run harness. This is
1130
blessed in to the IPC::Run package, so you may make later calls to
1131
functions as members if you like:
1132
1133
$h = harness( ... );
1134
$h->start;
1135
$h->pump;
1136
$h->finish;
1137
1138
$h = start( .... );
1139
$h->pump;
1140
...
1141
1142
Of course, using method call syntax lets you deal with any IPC::Run
1143
subclasses that might crop up, but don't hold your breath waiting for
1144
any.
1145
1146
run() and finish() return TRUE when all subcommands exit with a 0 result
1147
code. B.
1148
1149
All routines raise exceptions (via die()) when error conditions are
1150
recognized. A non-zero command result is not treated as an error
1151
condition, since some commands are tests whose results are reported
1152
in their exit codes.
1153
1154
=head1 ROUTINES
1155
1156
=over
1157
1158
=cut
1159
1160
231
231
38815
use strict;
231
371
231
5584
1161
231
231
761
use warnings;
231
378
231
9033
1162
231
231
836
use Exporter ();
231
392
231
5810
1163
231
231
765
use vars qw{$VERSION @ISA @FILTER_IMP @FILTERS @API @EXPORT_OK %EXPORT_TAGS};
231
294
231
34544
1164
1165
BEGIN {
1166
231
231
573
$VERSION = '20260402.0';
1167
231
3728
@ISA = qw{ Exporter };
1168
1169
## We use @EXPORT for the end user's convenience: there's only one function
1170
## exported, it's homonymous with the module, it's an unusual name, and
1171
## it can be suppressed by "use IPC::Run ();".
1172
231
594
@FILTER_IMP = qw( input_avail get_more_input );
1173
231
632
@FILTERS = qw(
1174
new_appender
1175
new_chunker
1176
new_string_source
1177
new_string_sink
1178
);
1179
231
2492
@API = qw(
1180
run
1181
harness start pump pumpable finish
1182
signal kill_kill reap_nb
1183
io timer timeout
1184
close_terminal
1185
binary
1186
clearcache
1187
);
1188
231
1010
@EXPORT_OK = ( @API, @FILTER_IMP, @FILTERS, qw( Win32_MODE ) );
1189
231
5460
%EXPORT_TAGS = (
1190
'filter_imp' => \@FILTER_IMP,
1191
'all' => \@EXPORT_OK,
1192
'filters' => \@FILTERS,
1193
'api' => \@API,
1194
);
1195
1196
}
1197
1198
231
231
1036
use strict;
231
288
231
4034
1199
231
231
798
use warnings;
231
7800
231
8160
1200
231
231
66280
use IPC::Run::Debug;
231
497
231
14868
1201
231
231
1162
use Exporter;
231
270
231
6514
1202
231
231
1038
use Fcntl;
231
297
231
39565
1203
231
231
1104
use POSIX ();
231
283
231
8313
1204
1205
BEGIN {
1206
231
50
231
3720
if ( $] < 5.008 ) { require Symbol; }
0
0
1207
}
1208
231
231
750
use Carp;
231
360
231
9764
1209
231
231
955
use File::Spec ();
231
336
231
2944
1210
231
231
78903
use IO::Handle;
231
849902
231
21803
1211
require IPC::Run::IO;
1212
require IPC::Run::Timer;
1213
1214
231
231
1543
use constant Win32_MODE => $^O =~ /os2|Win32/i;
231
317
231
27330
1215
1216
BEGIN {
1217
231
50
231
2095
if (Win32_MODE) {
1218
0
0
0
0
eval "use IPC::Run::Win32Helper; 1;"
0
1219
or ( $@ && die )
1220
or die "$!";
1221
}
1222
else {
1223
231
50
231
13151
eval "use File::Basename; 1;" or die $!;
231
1172
231
576
231
14810
1224
}
1225
}
1226
1227
sub input_avail();
1228
sub get_more_input();
1229
1230
###############################################################################
1231
1232
##
1233
## Error constants, not too locale-dependent
1234
231
231
982
use vars qw( $_EIO $_EAGAIN );
231
267
231
9019
1235
231
231
65309
use Errno qw( EIO EAGAIN EPIPE );
231
211930
231
29703
1236
1237
BEGIN {
1238
231
231
1308
local $!;
1239
231
405
$! = EIO;
1240
231
5286
$_EIO = qr/^$!/;
1241
231
473
$! = EAGAIN;
1242
231
19657
$_EAGAIN = qr/^$!/;
1243
}
1244
1245
##
1246
## State machine states, set in $self->{STATE}
1247
##
1248
## These must be in ascending order numerically
1249
##
1250
sub _newed() { 0 }
1251
sub _harnessed() { 1 }
1252
sub _finished() { 2 } ## _finished behave almost exactly like _harnessed
1253
sub _started() { 3 }
1254
1255
##
1256
## Which fds have been opened in the parent. This may have extra fds, since
1257
## we aren't all that rigorous about closing these off, but that's ok. This
1258
## is used on Unixish OSs to close all fds in the child that aren't needed
1259
## by that particular child.
1260
my %fds;
1261
1262
## There's a bit of hackery going on here.
1263
##
1264
## We want to have any code anywhere be able to emit
1265
## debugging statements without knowing what harness the code is
1266
## being called in/from, since we'd need to pass a harness around to
1267
## everything.
1268
##
1269
## Thus, $cur_self was born.
1270
1271
231
231
1307
use vars qw( $cur_self );
231
329
231
538730
1272
1273
sub _debug_fd {
1274
## STDERR may be tied to a handle that doesn't implement FILENO (e.g. a
1275
## tied filehandle without a real underlying fd). Wrap fileno() in eval
1276
## so we degrade gracefully instead of dying with "Can't locate object
1277
## method FILENO". Returns undef when no real fd is available, which is
1278
## safe: callers that receive undef simply skip debug-fd setup.
1279
3719
3719
5091
my $stderr_fd = eval { fileno STDERR };
3719
9239
1280
1281
3719
50
7909
return $stderr_fd unless defined $cur_self;
1282
1283
3719
50
33
60810
if ( _debugging && !defined $cur_self->{DEBUG_FD} ) {
1284
0
0
0
if ( defined $stderr_fd ) {
1285
0
0
my $fd = select STDERR;
1286
0
0
$| = 1;
1287
0
0
select $fd;
1288
0
0
$cur_self->{DEBUG_FD} = POSIX::dup $stderr_fd;
1289
0
0
0
_debug("debugging fd is $cur_self->{DEBUG_FD}\n")
1290
if _debugging_details;
1291
}
1292
}
1293
1294
3719
50
19365
return $stderr_fd unless defined $cur_self->{DEBUG_FD};
1295
1296
0
0
return $cur_self->{DEBUG_FD};
1297
}
1298
1299
sub DESTROY {
1300
## We absolutely do not want to do anything else here. We are likely
1301
## to be in a child process and we don't want to do things like kill_kill
1302
## ourself or cause other destruction.
1303
2470
2470
335394
my IPC::Run $self = shift;
1304
2470
50
8889
POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
1305
2470
6766
$self->{DEBUG_FD} = undef;
1306
1307
2470
9695
for my $kid ( @{$self->{KIDS}} ) {
2470
13898
1308
2384
3920
for my $op ( @{$kid->{OPS}} ) {
2384
54365
1309
4085
214426
delete $op->{FILTERS};
1310
}
1311
}
1312
}
1313
1314
##
1315
## Support routines (NOT METHODS)
1316
##
1317
my %cmd_cache;
1318
my $_cmd_cache_path = ''; # value of $ENV{PATH} when %cmd_cache was last populated
1319
1320
=item clearcache()
1321
1322
Clears the cache of executable paths that IPC::Run maintains internally.
1323
IPC::Run caches the full path of each command it resolves via C<$PATH> to
1324
avoid repeated filesystem searches. If you change C<$PATH> at runtime (or
1325
install a new executable into a directory that is already on C<$PATH>), call
1326
C to force IPC::Run to search C<$PATH> again on the next run.
1327
1328
local $ENV{PATH} = "/new/bin:$ENV{PATH}";
1329
IPC::Run::clearcache();
1330
run ['mycommand'], ...;
1331
1332
The cache is also invalidated automatically whenever C<$ENV{PATH}> changes
1333
between calls.
1334
1335
=cut
1336
1337
sub clearcache {
1338
10
10
1
725306
%cmd_cache = ();
1339
10
68
$_cmd_cache_path = '';
1340
10
61
return;
1341
}
1342
1343
sub _search_path {
1344
2149
2149
156202
my ($cmd_name) = @_;
1345
2149
100
66
12322
croak "command name is undefined or empty"
1346
unless defined $cmd_name && length $cmd_name;
1347
2148
100
66
132428
if ( File::Spec->file_name_is_absolute($cmd_name) && -x $cmd_name ) {
1348
1711
50
40730
_debug "'", $cmd_name, "' is absolute"
1349
if _debugging_details;
1350
1711
7908
return $cmd_name;
1351
}
1352
1353
437
50
7482
my $dirsep = (
50
100
1354
Win32_MODE ? '[/\\\\]'
1355
: $^O =~ /MacOS/ ? ':'
1356
: $^O =~ /VMS/ ? '[\[\]]'
1357
: '/'
1358
);
1359
1360
437
50
66
1699
if ( Win32_MODE
66
1361
&& ( $cmd_name =~ /$dirsep/ )
1362
&& ( $cmd_name !~ m!\.[^\\/\.]+$! ) ) {
1363
1364
5
50
213
_debug "no extension(.exe), checking ENV{PATHEXT}" if _debugging;
1365
5
50
24
for ( split /;/, $ENV{PATHEXT} || ".COM;.BAT;.EXE" ) {
1366
12
17
my $name = "$cmd_name$_";
1367
12
100
66
308
$cmd_name = $name, last if -f $name && -x _;
1368
}
1369
5
50
97
_debug "cmd_name is now '$cmd_name'" if _debugging;
1370
}
1371
1372
437
100
4858
if ( $cmd_name =~ /($dirsep)/ ) {
1373
6
50
101
_debug "'$cmd_name' contains '$1'" if _debugging;
1374
6
100
314
croak "file not found: $cmd_name" unless -e $cmd_name;
1375
5
50
49
croak "not a file: $cmd_name" unless -f $cmd_name;
1376
5
50
30
croak "permission denied: $cmd_name" unless -x $cmd_name;
1377
5
16
return $cmd_name;
1378
}
1379
1380
# Invalidate the entire cache when $PATH has changed so that commands are
1381
# re-resolved against the new search path (analogous to the shell "rehash").
1382
431
100
2358
my $current_path = defined $ENV{PATH} ? $ENV{PATH} : '';
1383
431
100
1316
if ( $current_path ne $_cmd_cache_path ) {
1384
103
50
3340
_debug "PATH changed, clearing cmd_cache" if _debugging;
1385
103
235
%cmd_cache = ();
1386
103
327
$_cmd_cache_path = $current_path;
1387
}
1388
1389
431
100
1373
if ( exists $cmd_cache{$cmd_name} ) {
1390
328
50
7260
_debug "'$cmd_name' found in cache: '$cmd_cache{$cmd_name}'"
1391
if _debugging;
1392
328
50
14254
return $cmd_cache{$cmd_name} if -x $cmd_cache{$cmd_name};
1393
0
0
0
_debug "'$cmd_cache{$cmd_name}' no longer executable, searching..."
1394
if _debugging;
1395
0
0
delete $cmd_cache{$cmd_name};
1396
}
1397
1398
103
133
my @searched_in;
1399
1400
## This next bit is Unix/Win32 specific, unfortunately.
1401
## There's been some conversation about extending File::Spec to provide
1402
## a universal interface to PATH, but I haven't seen it yet.
1403
103
50
902
my $re = Win32_MODE ? qr/;/ : qr/:/;
1404
1405
LOOP:
1406
103
100
2297
for ( split( $re, $ENV{PATH} || '', -1 ) ) {
1407
630
50
1039
$_ = "." unless length $_;
1408
630
979
push @searched_in, $_;
1409
1410
630
5155
my $prospect = File::Spec->catfile( $_, $cmd_name );
1411
630
988
my @prospects;
1412
1413
@prospects =
1414
( Win32_MODE && !( -f $prospect && -x _ ) )
1415
630
50
33
2996
? map "$prospect$_", split /;/, $ENV{PATHEXT} || ".COM;.BAT;.EXE"
0
1416
: ($prospect);
1417
1418
630
837
for my $found (@prospects) {
1419
630
100
66
22426
if ( -f $found && -x _ ) {
1420
102
487
$cmd_cache{$cmd_name} = $found;
1421
102
302
last LOOP;
1422
}
1423
}
1424
}
1425
1426
103
100
689
if ( exists $cmd_cache{$cmd_name} ) {
1427
102
50
2320
_debug "'", $cmd_name, "' added to cache: '", $cmd_cache{$cmd_name}, "'"
1428
if _debugging_details;
1429
102
650
return $cmd_cache{$cmd_name};
1430
}
1431
1432
1
189
croak "Command '$cmd_name' not found in " . join( ", ", @searched_in );
1433
}
1434
1435
# Translate a command or CODE reference (a $kid->{VAL}) to a list of strings
1436
# suitable for passing to _debug().
1437
sub _debugstrings {
1438
0
0
0
my $operand = shift;
1439
0
0
0
if ( !defined $operand ) {
1440
0
0
return '';
1441
}
1442
1443
0
0
my $ref = ref $operand;
1444
0
0
0
if ( !$ref ) {
0
0
1445
0
0
0
return length $operand < 50
1446
? "'$operand'"
1447
: join( '', "'", substr( $operand, 0, 10 ), "...'" );
1448
}
1449
elsif ( $ref eq 'ARRAY' ) {
1450
return (
1451
0
0
0
'[ ',
1452
join( " ", map /[^\w.-]/ ? "'$_'" : $_, @$operand ),
1453
' ]'
1454
);
1455
}
1456
elsif ( UNIVERSAL::isa( $operand, 'IPC::Run::Win32Process' ) ) {
1457
0
0
return "$operand";
1458
}
1459
0
0
return $ref;
1460
}
1461
1462
11547
100
11547
66945
sub _empty($) { !( defined $_[0] && length $_[0] ) }
1463
1464
## 'safe' versions of otherwise fun things to do. See also IPC::Run::Win32Helper.
1465
sub _close {
1466
12283
50
12283
29718
confess 'undef' unless defined $_[0];
1467
12283
50
167547
my $fd = $_[0] =~ /^\d+$/ ? $_[0] : fileno $_[0];
1468
12283
50
104125
if (Win32_MODE) {
1469
1470
# Perl close() or POSIX::close() on the read end of a pipe hangs if
1471
# another process is in a read attempt on the same pipe
1472
# (https://github.com/Perl/perl5/issues/19963). Since IPC::Run creates
1473
# pipes and shares them with user-defined kids, it's affected. Work
1474
# around that by first using dup2() to replace the FD with a non-pipe.
1475
# Unfortunately, for socket FDs, dup2() closes the SOCKET with
1476
# CloseHandle(). CloseHandle() documentation leaves its behavior
1477
# undefined for sockets. However, tests on Windows Server 2022 did not
1478
# leak memory, leak ports, or reveal any other obvious trouble.
1479
#
1480
# No failure here is fatal. (_close() has worked that way, either due
1481
# to a principle or just due to a history of callers passing closed
1482
# FDs.) croak() on EMFILE would be a bad user experience. Better to
1483
# proceed and hope that $fd is not a being-read pipe.
1484
#
1485
# Since start() and other user-facing methods _close() many FDs, we
1486
# could optimize this by opening and closing the non-pipe FD just once
1487
# per method call. The overhead of this simple approach was in the
1488
# noise, however.
1489
0
0
my $nul_fd = POSIX::open 'NUL';
1490
0
0
0
if ( !defined $nul_fd ) {
1491
0
0
0
_debug "open( NUL ) = ERROR $!" if _debugging_details;
1492
}
1493
else {
1494
0
0
my $r = POSIX::dup2( $nul_fd, $fd );
1495
0
0
0
0
_debug "dup2( $nul_fd, $fd ) = ERROR $!"
1496
if _debugging_details && !defined $r;
1497
0
0
$r = POSIX::close $nul_fd;
1498
0
0
0
0
_debug "close( $nul_fd (NUL) ) = ERROR $!"
1499
if _debugging_details && !defined $r;
1500
}
1501
}
1502
12283
199593
my $r = POSIX::close $fd;
1503
12283
100
34051
$r = $r ? '' : " ERROR $!";
1504
12283
160193
delete $fds{$fd};
1505
12283
50
0
315410
_debug "close( $fd ) = " . ( $r || 0 ) if _debugging_details;
1506
}
1507
1508
sub _dup {
1509
2279
50
2279
4788
confess 'undef' unless defined $_[0];
1510
2279
11024
my $r = POSIX::dup( $_[0] );
1511
2279
50
4014
croak "$!: dup( $_[0] )" unless defined $r;
1512
2279
50
4860
$r = 0 if $r eq '0 but true';
1513
2279
50
39012
_debug "dup( $_[0] ) = $r" if _debugging_details;
1514
2279
6119
$fds{$r} = {};
1515
2279
6026
return $r;
1516
}
1517
1518
sub _dup2_rudely {
1519
365
50
33
365
5313
confess 'undef' unless defined $_[0] && defined $_[1];
1520
365
3647
my $r = POSIX::dup2( $_[0], $_[1] );
1521
365
50
1881
croak "$!: dup2( $_[0], $_[1] )" unless defined $r;
1522
365
100
2428
$r = 0 if $r eq '0 but true';
1523
365
50
9546
_debug "dup2( $_[0], $_[1] ) = $r" if _debugging_details;
1524
365
2070
$fds{$r} = {};
1525
365
1372
return $r;
1526
}
1527
1528
sub _exec {
1529
183
50
183
1984
confess 'undef passed' if grep !defined, @_;
1530
1531
# exec @_ or croak "$!: exec( " . join( ', ', @_ ) . " )";
1532
183
50
4791
_debug 'exec()ing ', join " ", map "'$_'", @_ if _debugging_details;
1533
1534
# {
1535
## Commented out since we don't call this on Win32.
1536
# # This works around the bug where 5.6.1 complains
1537
# # "Can't exec ...: No error" after an exec on NT, where
1538
# # exec() is simulated and actually returns in Perl's C
1539
# # code, though Perl's &exec does not...
1540
# no warnings "exec";
1541
#
1542
# # Just in case the no warnings workaround
1543
# # stops being a workaround, we don't want
1544
# # old values of $! causing spurious strerr()
1545
# # messages to appear in the "Can't exec" message
1546
# undef $!;
1547
183
807
exec { $_[0] } @_;
183
0
1548
1549
# }
1550
# croak "$!: exec( " . join( ', ', map "'$_'", @_ ) . " )";
1551
## Fall through so $! can be reported to parent.
1552
}
1553
1554
sub _sysopen {
1555
264
50
33
264
1494
confess 'undef' unless defined $_[0] && defined $_[1];
1556
264
50
5223
_debug sprintf( "O_RDONLY=0x%02x ", O_RDONLY ),
1557
sprintf( "O_WRONLY=0x%02x ", O_WRONLY ),
1558
sprintf( "O_RDWR=0x%02x ", O_RDWR ),
1559
sprintf( "O_TRUNC=0x%02x ", O_TRUNC ),
1560
sprintf( "O_CREAT=0x%02x ", O_CREAT ),
1561
sprintf( "O_APPEND=0x%02x ", O_APPEND ),
1562
if _debugging_details;
1563
264
13750
my $r = POSIX::open( $_[0], $_[1], 0666 );
1564
264
100
8189
croak "$!: open( $_[0], ", sprintf( "0x%03x", $_[1] ), " )" unless defined $r;
1565
242
50
5637
_debug "open( $_[0], ", sprintf( "0x%03x", $_[1] ), " ) = $r"
1566
if _debugging_data;
1567
242
1195
$fds{$r} = {};
1568
242
735
return $r;
1569
}
1570
1571
sub _pipe {
1572
## Normal, blocking write for pipes that we read and the child writes,
1573
## since most children expect writes to stdout to block rather than
1574
## do a partial write.
1575
5353
5353
98015
my ( $r, $w ) = POSIX::pipe;
1576
5353
50
13277
croak "$!: pipe()" unless defined $r;
1577
5353
50
98682
_debug "pipe() = ( $r, $w ) " if _debugging_details;
1578
5353
32955
@fds{$r, $w} = ( {}, {} );
1579
5353
24856
return ( $r, $w );
1580
}
1581
1582
sub _pipe_nb {
1583
## For pipes that we write, unblock the write side, so we can fill a buffer
1584
## and continue to select().
1585
## Contributed by Borislav Deianov , with minor
1586
## bugfix on fcntl result by me.
1587
1138
1138
7371
local ( *R, *W );
1588
1138
60130
my $f = pipe( R, W );
1589
1138
50
6641
croak "$!: pipe()" unless defined $f;
1590
1138
11221
my ( $r, $w ) = ( fileno R, fileno W );
1591
1138
50
27008
_debug "pipe_nb pipe() = ( $r, $w )" if _debugging_details;
1592
1138
50
4793
unless (Win32_MODE) {
1593
## POSIX::fcntl doesn't take fd numbers, so gotta use Perl's and
1594
## then _dup the originals (which get closed on leaving this block)
1595
1138
10522
my $fres = fcntl( W, &F_SETFL, O_WRONLY | O_NONBLOCK );
1596
1138
50
4830
croak "$!: fcntl( $w, F_SETFL, O_NONBLOCK )" unless $fres;
1597
1138
50
21299
_debug "fcntl( $w, F_SETFL, O_NONBLOCK )" if _debugging_details;
1598
}
1599
1138
6299
( $r, $w ) = ( _dup($r), _dup($w) );
1600
1138
50
16845
_debug "pipe_nb() = ( $r, $w )" if _debugging_details;
1601
1138
17217
return ( $r, $w );
1602
}
1603
1604
sub _pty {
1605
35
35
131
require IO::Pty;
1606
35
504
my $pty = IO::Pty->new();
1607
35
50
15880
croak "$!: pty ()" unless $pty;
1608
35
96
$pty->autoflush();
1609
35
50
1065
$pty->blocking(0) or croak "$!: pty->blocking ( 0 )";
1610
35
50
984
_debug "pty() = ( ", $pty->fileno, ", ", $pty->slave->fileno, " )"
1611
if _debugging_details;
1612
35
309
@fds{ $pty->fileno, $pty->slave->fileno } = ( {}, {} );
1613
35
822
return $pty;
1614
}
1615
1616
sub _read {
1617
6752
50
6752
22453
confess 'undef' unless defined $_[0];
1618
6752
29428
my $s = '';
1619
6752
8814
my $r;
1620
do {
1621
6753
2818299899
$r = POSIX::read( $_[0], $s, 10_000 );
1622
6752
100
9412
} while ( !defined($r) && $!{EINTR} );
1623
6752
100
34174
croak "$!: read( $_[0] )" unless defined($r);
1624
6731
50
20635
$r ||= 0;
1625
6731
50
241383
_debug "read( $_[0] ) = $r chars '$s'" if _debugging_data;
1626
6731
42623
return $s;
1627
}
1628
1629
## A METHOD, not a function.
1630
sub _spawn {
1631
2403
2403
3587
my IPC::Run $self = shift;
1632
2403
5939
my ($kid) = @_;
1633
1634
croak "Can't spawn IPC::Run::Win32Process except on Win32"
1635
2403
50
9022
if UNIVERSAL::isa( $kid->{VAL}, 'IPC::Run::Win32Process' );
1636
1637
2403
50
40090
_debug "opening sync pipe ", $kid->{PID} if _debugging_details;
1638
2403
4885
my $sync_reader_fd;
1639
2403
10045
( $sync_reader_fd, $self->{SYNC_WRITER_FD} ) = _pipe;
1640
1641
## GH#122: For CODE ref children, create a separate pipe to propagate
1642
## exceptions back to the parent. We can't reuse the sync pipe because
1643
## it must be closed before the CODE ref runs (to unblock the parent),
1644
## but we still need a channel for the child to report die() messages.
1645
2403
3806
my $coderef_err_reader_fd;
1646
2403
100
8130
if ( ref $kid->{VAL} eq 'CODE' ) {
1647
346
1045
( $coderef_err_reader_fd, $self->{CODEREF_ERR_FD} ) = _pipe;
1648
}
1649
1650
2403
4911901
$kid->{PID} = fork();
1651
2403
50
79057
croak "$! during fork" unless defined $kid->{PID};
1652
1653
2403
100
18001
unless ( $kid->{PID} ) {
1654
186
50
23144
if ( $self->{_sigusr1_after_fork} ) {
1655
1656
# sleep 10ms to improve chance of parent starting read() before it
1657
# handles the signal we're about to send.
1658
0
0
select undef, undef, undef, 0.01;
1659
0
0
kill 'USR1', getppid;
1660
}
1661
## Close the parent's reader end of the error pipe in the child.
1662
186
100
10284
POSIX::close $coderef_err_reader_fd if defined $coderef_err_reader_fd;
1663
## _do_kid_and_exit closes sync_reader_fd since it closes all unwanted and
1664
## unloved fds.
1665
186
20059
$self->_do_kid_and_exit($kid);
1666
}
1667
2217
50
862267
_debug "fork() = ", $kid->{PID} if _debugging_details;
1668
1669
## Close the child's writer end of the error pipe in the parent.
1670
2217
100
27027
if ( defined $self->{CODEREF_ERR_FD} ) {
1671
343
5271
POSIX::close $self->{CODEREF_ERR_FD};
1672
343
11010
$kid->{CODEREF_ERR_FD} = $coderef_err_reader_fd;
1673
}
1674
1675
## Wait for kid to get to its exec() and see if it fails.
1676
2217
193611
_close $self->{SYNC_WRITER_FD};
1677
2217
31258
my $sync_pulse = _read $sync_reader_fd;
1678
2217
14846
_close $sync_reader_fd;
1679
1680
2217
100
66
35725
if ( !defined $sync_pulse || length $sync_pulse ) {
1681
2
50
3076
if ( waitpid( $kid->{PID}, 0 ) >= 0 ) {
1682
2
38
$kid->{RESULT} = $?;
1683
}
1684
else {
1685
0
0
$kid->{RESULT} = -1;
1686
}
1687
2
50
16
$sync_pulse = "error reading synchronization pipe for $kid->{NUM}, pid $kid->{PID}"
1688
unless length $sync_pulse;
1689
2
779
croak $sync_pulse;
1690
}
1691
2215
20440
return $kid->{PID};
1692
}
1693
1694
sub _write {
1695
901
50
33
901
6790
confess 'undef' unless defined $_[0] && defined $_[1];
1696
901
18542
my $r = POSIX::write( $_[0], $_[1], length $_[1] );
1697
901
100
2733
unless ( defined $r ) {
1698
231
50
4667
return undef if $! == EPIPE; ## caller handles broken pipe
1699
0
0
0
return 0 if $! == EAGAIN; ## non-blocking pipe buffer full, retry later
1700
0
0
croak "$!: write( $_[0], '$_[1]' )";
1701
}
1702
670
50
16837
_debug "write( $_[0], '$_[1]' ) = $r" if _debugging_data;
1703
670
1644
return $r;
1704
}
1705
1706
=pod
1707
1708
=over
1709
1710
=item run
1711
1712
Run takes a harness or harness specification and runs it, pumping
1713
all input to the child(ren), closing the input pipes when no more
1714
input is available, collecting all output that arrives, until the
1715
pipes delivering output are closed, then waiting for the children to
1716
exit and reaping their result codes.
1717
1718
You may think of C as being like
1719
1720
start( ... )->finish();
1721
1722
, though there is one subtle difference: run() does not
1723
set \$input_scalars to '' like finish() does. If an exception is thrown
1724
from run(), all children will be killed off "gently", and then "annihilated"
1725
if they do not go gently (in to that dark night. sorry).
1726
1727
If any exceptions are thrown, this does a L before propagating
1728
them.
1729
1730
=cut
1731
1732
231
231
95422
use vars qw( $in_run ); ## No, not Enron;)
231
322
231
2437582
1733
1734
sub run {
1735
2177
2177
1
12814036
local $in_run = 1; ## Allow run()-only optimizations.
1736
2177
12914
my IPC::Run $self = start(@_);
1737
1857
9290
my $r = eval {
1738
1857
6256
$self->{clear_ins} = 0;
1739
1857
23407
$self->finish;
1740
};
1741
1857
100
5414
if ($@) {
1742
45
399
my $x = $@;
1743
45
405
$self->kill_kill;
1744
45
763
die $x;
1745
}
1746
1812
19385
return $r;
1747
}
1748
1749
=pod
1750
1751
=item signal
1752
1753
## To send it a specific signal by name ("USR1"):
1754
signal $h, "USR1";
1755
$h->signal ( "USR1" );
1756
1757
If $signal is provided and defined, sends a signal to all child processes. Try
1758
not to send numeric signals, use C<"KILL"> instead of C<9>, for instance.
1759
Numeric signals aren't portable.
1760
1761
Throws an exception if $signal is undef.
1762
1763
This will I clean up the harness, C it if you kill it.
1764
1765
Normally TERM kills a process gracefully (this is what the command line utility
1766
C does by default), INT is sent by one of the keys C<^C>, C or
1767
CDelE>, and C is used to kill a process and make it coredump.
1768
1769
The C signal is often used to get a process to "restart", rereading
1770
config files, and C and C for really application-specific things.
1771
1772
Often, running C (that's a lower case "L") on the command line will
1773
list the signals present on your operating system.
1774
1775
B: The signal subsystem is not at all portable. We *may* offer
1776
to simulate C and C on some operating systems, submit code
1777
to me if you want this.
1778
1779
B: Up to and including perl v5.6.1, doing almost anything in a
1780
signal handler could be dangerous. The most safe code avoids all
1781
mallocs and system calls, usually by preallocating a flag before
1782
entering the signal handler, altering the flag's value in the
1783
handler, and responding to the changed value in the main system:
1784
1785
my $got_usr1 = 0;
1786
sub usr1_handler { ++$got_signal }
1787
1788
$SIG{USR1} = \&usr1_handler;
1789
while () { sleep 1; print "GOT IT" while $got_usr1--; }
1790
1791
Even this approach is perilous if ++ and -- aren't atomic on your system
1792
(I've never heard of this on any modern CPU large enough to run perl).
1793
1794
=cut
1795
1796
sub signal {
1797
69
69
1
1623
my IPC::Run $self = shift;
1798
1799
69
157
local $cur_self = $self;
1800
1801
69
50
671
$self->_kill_kill_kill_pussycat_kill unless @_;
1802
1803
69
50
557
Carp::cluck "Ignoring extra parameters passed to kill()" if @_ > 1;
1804
1805
69
435
my ($signal) = @_;
1806
69
50
447
croak "Undefined signal passed to signal" unless defined $signal;
1807
69
66
223
for ( grep $_->{PID} && !defined $_->{RESULT}, @{ $self->{KIDS} } ) {
69
1854
1808
28
50
1018
_debug "sending $signal to $_->{PID}"
1809
if _debugging;
1810
kill $signal, $_->{PID}
1811
28
50
0
981
or _debugging && _debug "$! sending $signal to $_->{PID}";
1812
}
1813
1814
69
586
return;
1815
}
1816
1817
=pod
1818
1819
=item kill_kill
1820
1821
## To kill off a process:
1822
$h->kill_kill;
1823
kill_kill $h;
1824
1825
## To specify the grace period other than 30 seconds:
1826
kill_kill $h, grace => 5;
1827
1828
## To send QUIT instead of KILL if a process refuses to die:
1829
kill_kill $h, coup_d_grace => "QUIT";
1830
1831
Sends a C, waits for all children to exit for up to 30 seconds, then
1832
sends a C to any that survived the C.
1833
1834
Will wait for up to 30 more seconds for the OS to successfully C the
1835
processes.
1836
1837
The 30 seconds may be overridden by setting the C option, this
1838
overrides both timers.
1839
1840
The harness is then cleaned up.
1841
1842
The doubled name indicates that this function may kill again and avoids
1843
colliding with the core Perl C function.
1844
1845
Returns undef if the C was sufficient, or a 1 if C was
1846
required. Throws an exception if C did not permit the children
1847
to be reaped.
1848
1849
B: The grace period is actually up to 1 second longer than that
1850
given. This is because the granularity of C is 1 second. Let me
1851
know if you need finer granularity, we can leverage Time::HiRes here.
1852
1853
B: Win32 does not support signals, so C is sent immediately
1854
instead of C. The return value is C when the process exits
1855
after the initial C, or C<1> if a second C was needed. Grace
1856
periods have no meaning on Win32.
1857
1858
=cut
1859
1860
sub kill_kill {
1861
63
63
1
2965
my IPC::Run $self = shift;
1862
1863
63
413
my %options = @_;
1864
63
492
my $grace = $options{grace};
1865
63
100
519
$grace = 30 unless defined $grace;
1866
63
310
++$grace; ## Make grace time a _minimum_
1867
1868
63
351
my $coup_d_grace = $options{coup_d_grace};
1869
63
50
654
$coup_d_grace = "KILL" unless defined $coup_d_grace;
1870
1871
63
1840
delete $options{$_} for qw( grace coup_d_grace );
1872
63
50
418
Carp::cluck "Ignoring unknown options for kill_kill: ",
1873
join " ", keys %options
1874
if keys %options;
1875
1876
63
50
1060
if (Win32_MODE) {
1877
# immediate brutal death for Win32
1878
# TERM has unfortunate side-effects
1879
0
0
$self->signal("KILL")
1880
}
1881
else {
1882
63
339
$self->signal("TERM");
1883
}
1884
1885
63
448
my $quitting_time = time + $grace;
1886
63
120
my $delay = 0.01;
1887
63
135
my $accum_delay;
1888
1889
my $have_killed_before;
1890
1891
63
211
while () {
1892
## delay first to yield to other processes
1893
72
2770883
select undef, undef, undef, $delay;
1894
72
1164
$accum_delay += $delay;
1895
1896
72
977
$self->reap_nb;
1897
72
100
489
last unless $self->_running_kids;
1898
1899
9
100
38
if ( $accum_delay >= $grace * 0.8 ) {
1900
## No point in checking until delay has grown some.
1901
2
100
27
if ( time >= $quitting_time ) {
1902
1
50
25
if ( !$have_killed_before ) {
1903
1
9
$self->signal($coup_d_grace);
1904
1
3
$have_killed_before = 1;
1905
1
3
$quitting_time += $grace;
1906
1
10
$delay = 0.01;
1907
1
3
$accum_delay = 0;
1908
1
5
next;
1909
}
1910
0
0
croak "Unable to reap all children, even after KILLing them";
1911
}
1912
}
1913
1914
8
24
$delay *= 2;
1915
8
100
32
$delay = 0.5 if $delay >= 0.5;
1916
}
1917
1918
63
430
$self->_cleanup;
1919
63
222
return $have_killed_before;
1920
}
1921
1922
=pod
1923
1924
=item harness
1925
1926
Takes a harness specification and returns a harness. This harness is
1927
blessed in to IPC::Run, allowing you to use method call syntax for
1928
run(), start(), et al if you like.
1929
1930
harness() is provided so that you can pre-build harnesses if you
1931
would like to, but it's not required..
1932
1933
You may proceed to run(), start() or pump() after calling harness() (pump()
1934
calls start() if need be). Alternatively, you may pass your
1935
harness specification to run() or start() and let them harness() for
1936
you. You can't pass harness specifications to pump(), though.
1937
1938
=cut
1939
1940
##
1941
## Notes: I've avoided handling a scalar that doesn't look like an
1942
## opcode as a here document or as a filename, though I could DWIM
1943
## those. I'm not sure that the advantages outweigh the danger when
1944
## the DWIMer guesses wrong.
1945
##
1946
## TODO: allow user to spec default shell. Hmm, globally, in the
1947
## lexical scope hash, or per instance? 'Course they can do that
1948
## now by using a [...] to hold the command.
1949
##
1950
my $harness_id = 0;
1951
1952
sub harness {
1953
2702
2702
1
5171424
my $options;
1954
2702
50
66
25044
if ( @_ && ref $_[-1] eq 'HASH' ) {
1955
0
0
$options = pop;
1956
0
0
require Data::Dumper;
1957
0
0
carp "Passing in options as a hash is deprecated:\n", Data::Dumper::Dumper($options);
1958
}
1959
1960
# local $IPC::Run::debug = $options->{debug}
1961
# if $options && defined $options->{debug};
1962
1963
2702
4481
my @args;
1964
2702
100
100
35332
if ( @_ == 1 && !ref $_[0] ) {
100
100
1965
105
50
421
if (Win32_MODE) {
1966
0
0
0
my $command = $ENV{ComSpec} || 'cmd';
1967
0
0
@args = ( [ $command, '/c', win32_parse_cmd_line $_[0] ] );
1968
}
1969
else {
1970
105
421
@args = ( [ qw( sh -c ), @_ ] );
1971
}
1972
}
1973
elsif ( @_ > 1 && !grep ref $_, @_ ) {
1974
101
859
@args = ( [@_] );
1975
}
1976
else {
1977
@args = map {
1978
2496
100
4894
if ( !defined $_ ) {
11854
16228
1979
37
100
159
if ( Internals::SvREADONLY($_) ) {
1980
30
67
my $undef;
1981
30
417
bless \$undef, 'IPC::Run::Undef';
1982
}
1983
else {
1984
7
61
bless \$_, 'IPC::Run::Undef';
1985
}
1986
}
1987
else {
1988
11817
23272
$_;
1989
}
1990
} @_;
1991
}
1992
1993
2702
8972
my @errs; # Accum errors, emit them when done.
1994
1995
my $succinct; # set if no redir ops are required yet. Cleared
1996
# if an op is seen.
1997
1998
2702
0
my $cur_kid; # references kid or handle being parsed
1999
2702
4826
my $next_kid_close_stdin = 0;
2000
2001
2702
4319
my $assumed_fd = 0; # fd to assume in succinct mode (no redir ops)
2002
2702
3731
my $handle_num = 0; # 1... is which handle we're parsing
2003
2004
2702
14067
my IPC::Run $self = bless {}, __PACKAGE__;
2005
2006
2702
25071
local $cur_self = $self;
2007
2008
2702
9796
$self->{ID} = ++$harness_id;
2009
2702
7000
$self->{IOS} = [];
2010
2702
6208
$self->{KIDS} = [];
2011
2702
5972
$self->{PIPES} = [];
2012
2702
5913
$self->{PTYS} = {};
2013
2702
6277
$self->{TIMERS} = [];
2014
2702
9264
$self->{STATE} = _newed;
2015
2016
2702
50
6995
if ($options) {
2017
0
0
$self->{$_} = $options->{$_} for keys %$options;
2018
}
2019
2020
2702
50
76540
_debug "****** harnessing *****" if _debugging;
2021
2022
2702
4124
my $first_parse;
2023
2702
4502
local $_;
2024
2702
5264
my $arg_count = @args;
2025
2702
6325
while (@args) {
2026
8984
16471
for ( shift @args ) {
2027
8984
13702
eval {
2028
8984
9875
$first_parse = 1;
2029
8984
50
184100
_debug( "parsing ", _debugstrings($_) ) if _debugging;
2030
2031
REPARSE:
2032
11417
100
66
351257
if ( ref eq 'ARRAY'
100
100
100
100
100
100
100
100
100
100
100
66
100
66
100
66
100
66
100
100
100
100
100
100
100
33
50
50
50
2033
|| UNIVERSAL::isa( $_, 'IPC::Run::Win32Process' )
2034
|| ( !$cur_kid && ref eq 'CODE' ) ) {
2035
2641
50
5679
croak "Process control symbol ('|', '&') missing" if $cur_kid;
2036
2641
50
33
11441
croak "Can't spawn a subroutine on Win32"
2037
if Win32_MODE && ref eq "CODE";
2038
2641
100
100
26295
croak "Can't run undefined command. Did you pass a reference to an undefined array?"
100
2039
if ref eq 'ARRAY' && @$_ && !defined( $_->[0] );
2040
$cur_kid = {
2041
TYPE => 'cmd',
2042
VAL => $_,
2043
2638
4921
NUM => @{ $self->{KIDS} } + 1,
2638
19785
2044
OPS => [],
2045
PID => '',
2046
RESULT => undef,
2047
};
2048
2049
2638
100
6688
unshift @{ $cur_kid->{OPS} }, {
34
208
2050
TYPE => 'close',
2051
KFD => 0,
2052
} if $next_kid_close_stdin;
2053
2638
3614
$next_kid_close_stdin = 0;
2054
2055
2638
3615
push @{ $self->{KIDS} }, $cur_kid;
2638
6860
2056
2638
4363
$succinct = 1;
2057
}
2058
2059
elsif ( UNIVERSAL::isa( $_, 'IPC::Run::IO' ) ) {
2060
2
4
push @{ $self->{IOS} }, $_;
2
6
2061
2
3
$cur_kid = undef;
2062
2
4
$succinct = 1;
2063
}
2064
2065
elsif ( UNIVERSAL::isa( $_, 'IPC::Run::Timer' ) ) {
2066
400
576
push @{ $self->{TIMERS} }, $_;
400
830
2067
400
624
$succinct = 1;
2068
}
2069
2070
elsif ( ref $_ eq 'IPC::Run::Undef' ) {
2071
## Silently ignore undef values passed where a timer or
2072
## other optional argument would go (e.g. undef timeout).
2073
## See https://github.com/cpan-authors/IPC-Run/issues/128
2074
}
2075
2076
elsif (/^(\d*)>&(\d+)$/) {
2077
74
100
1900
croak "No command before '$_'" unless $cur_kid;
2078
64
50
159
push @{ $cur_kid->{OPS} }, {
64
510
2079
TYPE => 'dup',
2080
KFD1 => $2,
2081
KFD2 => length $1 ? $1 : 1,
2082
};
2083
64
50
893
_debug "redirect operators now required" if _debugging_details;
2084
64
136
$succinct = !$first_parse;
2085
}
2086
2087
elsif (/^(\d*)<&(\d+)$/) {
2088
34
100
1380
croak "No command before '$_'" unless $cur_kid;
2089
24
50
72
push @{ $cur_kid->{OPS} }, {
24
312
2090
TYPE => 'dup',
2091
KFD1 => $2,
2092
KFD2 => length $1 ? $1 : 0,
2093
};
2094
24
72
$succinct = !$first_parse;
2095
}
2096
2097
elsif (/^(\d*)<&-$/) {
2098
43
100
2545
croak "No command before '$_'" unless $cur_kid;
2099
23
50
253
push @{ $cur_kid->{OPS} }, {
23
391
2100
TYPE => 'close',
2101
KFD => length $1 ? $1 : 0,
2102
};
2103
23
115
$succinct = !$first_parse;
2104
}
2105
2106
elsif (/^(\d*) (
2107
|| /^(\d*) (
2108
|| /^(\d*) (
2109
|| /^(\d*) (<) () () (.*)$/x ) {
2110
1408
100
6539
croak "No command before '$_'" unless $cur_kid;
2111
2112
1388
3264
$succinct = !$first_parse;
2113
2114
1388
15210
my $type = $2 . $4;
2115
2116
1388
100
6255
my $kfd = length $1 ? $1 : 0;
2117
2118
1388
2326
my $pty_id;
2119
1388
100
3285
if ( $type eq '
2120
14
50
93
$pty_id = length $3 ? $3 : '0';
2121
## do the require here to cause early error reporting
2122
14
117
require IO::Pty;
2123
## Just flag the pyt's existence for now. It'll be
2124
## converted to a real IO::Pty by _open_pipes.
2125
14
47
$self->{PTYS}->{$pty_id} = undef;
2126
}
2127
2128
1388
4136
my $source = $5;
2129
2130
1388
1673
my @filters;
2131
1388
1868
my $binmode = 1;
2132
2133
1388
100
3325
unless ( length $source ) {
2134
1327
100
4752
if ( !$succinct ) {
2135
387
100
5669
while ( @args > 1
100
2136
&& ( ( ref $args[1] && !UNIVERSAL::isa( $args[1], "IPC::Run::Timer" ) && ref $args[1] ne 'IPC::Run::Undef' ) || UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) ) {
2137
64
100
243
if ( UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) {
2138
42
77
$binmode = shift(@args)->();
2139
}
2140
else {
2141
22
152
push @filters, shift @args;
2142
}
2143
}
2144
}
2145
1327
2378
$source = shift @args;
2146
1327
50
4330
croak "'$_' missing a source" if _empty $source;
2147
2148
_debug(
2149
1327
50
33
27093
'Kid ', $cur_kid->{NUM}, "'s input fd ", $kfd,
2150
' has ', scalar(@filters), ' filters.'
2151
) if _debugging_details && @filters;
2152
}
2153
2154
1388
9421
my IPC::Run::IO $pipe = IPC::Run::IO->_new_internal( $type, $kfd, $pty_id, $source, $binmode, @filters );
2155
2156
1388
100
100
13517
if ( ( ref $source eq 'GLOB' || UNIVERSAL::isa $source, 'IO::Handle' )
100
100
2157
&& $type !~ /^
2158
## GH#57: For plain input redirects (<) on non-standard
2159
## fds, do NOT set DONT_CLOSE. After fork the parent no
2160
## longer needs the input handle — the child has its own
2161
## copy via dup2. Keeping it open prevents EPIPE/SIGPIPE
2162
## when the child exits early, which can hang the writer.
2163
## Protect stdin/stdout/stderr (fd 0-2) since closing
2164
## those in the parent would be destructive.
2165
66
518
my $fno = fileno $source;
2166
66
50
33
776
if ( defined $fno && $fno <= 2 ) {
2167
0
0
0
_debug "setting DONT_CLOSE for std fd" if _debugging_details;
2168
0
0
$pipe->{DONT_CLOSE} = 1;
2169
}
2170
66
50
440
_dont_inherit($source) if Win32_MODE;
2171
}
2172
2173
1388
2543
push @{ $cur_kid->{OPS} }, $pipe;
1388
4762
2174
}
2175
2176
elsif (
2177
/^() (>>?) (&) () (.*)$/x
2178
|| /^() (&) (>pipe) () () $/x
2179
|| /^() (>pipe)(&) () () $/x
2180
|| /^(\d*)() (>pipe) () () $/x
2181
|| /^() (&) (>pty) ( \w*)> () $/x
2182
## TODO: || /^() (>pty) (\d*)> (&) () $/x
2183
|| /^(\d*)() (>pty) ( \w*)> () $/x
2184
|| /^() (&) (>>?) () (.*)$/x || /^(\d*)() (>>?) () (.*)$/x
2185
) {
2186
2852
100
11439
croak "No command before '$_'" unless $cur_kid;
2187
2188
2822
4894
$succinct = !$first_parse;
2189
2190
2822
100
66
49873
my $type = (
100
66
2191
$2 eq '>pipe' || $3 eq '>pipe' ? '>pipe'
2192
: $2 eq '>pty' || $3 eq '>pty' ? '>pty>'
2193
: '>'
2194
);
2195
2822
100
9093
my $kfd = length $1 ? $1 : 1;
2196
2822
66
8522
my $trunc = !( $2 eq '>>' || $3 eq '>>' );
2197
2822
50
66
10492
my $pty_id = (
100
2198
$2 eq '>pty' || $3 eq '>pty'
2199
? length $4
2200
? $4
2201
: 0
2202
: undef
2203
);
2204
2205
2822
100
15674
my $stderr_too =
2206
$2 eq '&'
2207
|| $3 eq '&'
2208
|| ( !length $1 && substr( $type, 0, 4 ) eq '>pty' );
2209
2210
2822
6469
my $dest = $5;
2211
2822
3280
my @filters;
2212
2822
3248
my $binmode = 1;
2213
2822
100
5935
unless ( length $dest ) {
2214
2625
100
5161
if ( !$succinct ) {
2215
## unshift...shift: '>' filters source...sink left...right
2216
1132
100
7347
while ( @args > 1
100
2217
&& ( ( ref $args[1] && !UNIVERSAL::isa( $args[1], "IPC::Run::Timer" ) && ref $args[1] ne 'IPC::Run::Undef' ) || UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) ) {
2218
75
100
386
if ( UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) {
2219
49
100
$binmode = shift(@args)->();
2220
}
2221
else {
2222
26
180
unshift @filters, shift @args;
2223
}
2224
}
2225
}
2226
2227
2625
100
66
13102
if ( @args && ref $args[0] eq 'IPC::Run::Undef' ) {
2228
2
12
require Symbol;
2229
2
10
${ $args[0] } = $dest = Symbol::gensym();
2
32
2230
2
2
shift @args;
2231
}
2232
else {
2233
2623
4105
$dest = shift @args;
2234
}
2235
2236
_debug(
2237
2625
50
33
48724
'Kid ', $cur_kid->{NUM}, "'s output fd ", $kfd,
2238
' has ', scalar(@filters), ' filters.'
2239
) if _debugging_details && @filters;
2240
2241
2625
100
5346
if ( $type eq '>pty>' ) {
2242
## do the require here to cause early error reporting
2243
27
234
require IO::Pty;
2244
## Just flag the pyt's existence for now. _open_pipes()
2245
## will new an IO::Pty for each key.
2246
27
107
$self->{PTYS}->{$pty_id} = undef;
2247
}
2248
}
2249
2250
2822
50
5777
croak "'$_' missing a destination" if _empty $dest;
2251
2822
13238
my $pipe = IPC::Run::IO->_new_internal( $type, $kfd, $pty_id, $dest, $binmode, @filters );
2252
2822
7595
$pipe->{TRUNC} = $trunc;
2253
2254
2822
100
66
16599
if ( ( UNIVERSAL::isa( $dest, 'GLOB' ) || UNIVERSAL::isa( $dest, 'IO::Handle' ) )
100
2255
&& $type !~ /^>(pty>|pipe)$/ ) {
2256
60
50
1072
_debug "setting DONT_CLOSE" if _debugging_details;
2257
60
207
$pipe->{DONT_CLOSE} = 1; ## this FD is not closed by us.
2258
}
2259
2822
3533
push @{ $cur_kid->{OPS} }, $pipe;
2822
5530
2260
2822
100
7940
push @{ $cur_kid->{OPS} }, {
50
337
2261
TYPE => 'dup',
2262
KFD1 => 1,
2263
KFD2 => 2,
2264
} if $stderr_too;
2265
}
2266
2267
elsif ( $_ eq "|" ) {
2268
33
100
1260
croak "No command before '$_'" unless $cur_kid;
2269
23
127
unshift @{ $cur_kid->{OPS} }, {
23
166
2270
TYPE => '|',
2271
KFD => 1,
2272
};
2273
23
96
$succinct = 1;
2274
23
57
$assumed_fd = 1;
2275
23
68
$cur_kid = undef;
2276
}
2277
2278
elsif ( $_ eq "&" ) {
2279
44
100
1378
croak "No command before '$_'" unless $cur_kid;
2280
34
110
$next_kid_close_stdin = 1;
2281
34
168
$succinct = 1;
2282
34
74
$assumed_fd = 0;
2283
34
52
$cur_kid = undef;
2284
}
2285
2286
elsif ( $_ eq 'init' ) {
2287
89
50
705
croak "No command before '$_'" unless $cur_kid;
2288
89
355
push @{ $cur_kid->{OPS} }, {
89
714
2289
TYPE => 'init',
2290
SUB => shift @args,
2291
};
2292
}
2293
2294
elsif ( $_ eq 'env' ) {
2295
10
50
74
croak "No command before '$_'" unless $cur_kid;
2296
10
25
my $env = shift @args;
2297
10
100
310
croak "'env' option requires a hash reference" unless ref $env eq 'HASH';
2298
9
42
$cur_kid->{ENV} = $env;
2299
}
2300
2301
elsif ( !ref $_ ) {
2302
1319
5274
$self->{$_} = shift @args;
2303
}
2304
2305
elsif ( ref $_ eq 'IPC::Run::Undef' ) {
2306
## bare undef argument - silently ignore to preserve
2307
## pre-20180523.0 behavior where undef matched !ref $_ and
2308
## was absorbed as a no-op. See GH#124.
2309
}
2310
2311
elsif ( $_ eq 'init' ) {
2312
0
0
0
croak "No command before '$_'" unless $cur_kid;
2313
0
0
push @{ $cur_kid->{OPS} }, {
0
0
2314
TYPE => 'init',
2315
SUB => shift @args,
2316
};
2317
}
2318
2319
elsif ( $succinct && $first_parse ) {
2320
## It's not an opcode, and no explicit opcodes have been
2321
## seen yet, so assume it's a file name.
2322
2433
5509
unshift @args, $_;
2323
2433
100
4771
if ( !$assumed_fd ) {
2324
940
2884
$_ = "$assumed_fd<",
2325
}
2326
else {
2327
1493
3771
$_ = "$assumed_fd>",
2328
}
2329
2433
50
42955
_debug "assuming '", $_, "'" if _debugging_details;
2330
2433
3140
++$assumed_fd;
2331
2433
3172
$first_parse = 0;
2332
2433
140985
goto REPARSE;
2333
}
2334
2335
else {
2336
0
0
0
croak join(
2337
'',
2338
'Unexpected ',
2339
( ref() ? $_ : 'scalar' ),
2340
' in harness() parameter ',
2341
$arg_count - @args
2342
);
2343
}
2344
};
2345
8984
100
27253
if ($@) {
2346
114
280
push @errs, $@;
2347
114
50
10316
_debug 'caught ', $@ if _debugging;
2348
}
2349
}
2350
}
2351
2352
2702
100
5575
die join( '', @errs ) if @errs;
2353
2354
2588
4887
$self->{STATE} = _harnessed;
2355
2356
# $self->timeout( $options->{timeout} ) if exists $options->{timeout};
2357
2588
8511
return $self;
2358
}
2359
2360
sub _open_pipes {
2361
2435
2435
4471
my IPC::Run $self = shift;
2362
2363
2435
9442
my @errs;
2364
2365
my @close_on_fail;
2366
2367
## When a pipe character is seen, a pipe is created. $pipe_read_fd holds
2368
## the dangling read end of the pipe until we get to the next process.
2369
2435
0
my $pipe_read_fd;
2370
2371
## Output descriptors for the last command are shared by all children.
2372
## @output_fds_accum accumulates the current set of output fds.
2373
2435
0
my @output_fds_accum;
2374
2375
2435
3570
for ( sort keys %{ $self->{PTYS} } ) {
2435
11211
2376
36
50
552
_debug "opening pty '", $_, "'" if _debugging_details;
2377
36
50
eval {
2378
36
164
my $pty = _pty;
2379
35
113
$self->{PTYS}->{$_} = $pty;
2380
};
2381
36
100
138
if ($@) {
2382
1
2
push @errs, $@;
2383
1
50
13
_debug 'caught ', $@ if _debugging;
2384
}
2385
}
2386
2387
2435
7355
for ( @{ $self->{IOS} } ) {
2435
6584
2388
2
2
eval { $_->init; };
2
9
2389
2
50
5
if ($@) {
2390
0
0
push @errs, $@;
2391
0
0
0
_debug 'caught ', $@ if _debugging;
2392
}
2393
else {
2394
2
5
push @close_on_fail, $_;
2395
}
2396
}
2397
2398
## Loop through the kids and their OPS, interpreting any that require
2399
## parent-side actions.
2400
2435
3367
for my $kid ( @{ $self->{KIDS} } ) {
2435
10799
2401
2490
100
11998
if ( ref $kid->{VAL} eq 'ARRAY' ) {
2402
2144
12487
$kid->{PATH} = _search_path $kid->{VAL}->[0];
2403
}
2404
2487
100
11539
if ( defined $pipe_read_fd ) {
2405
23
50
570
_debug "placing write end of pipe on kid $kid->{NUM}'s stdin"
2406
if _debugging_details;
2407
23
32
unshift @{ $kid->{OPS} }, {
23
193
2408
TYPE => 'PIPE', ## Prevent next loop from triggering on this
2409
KFD => 0,
2410
TFD => $pipe_read_fd,
2411
};
2412
23
51
$pipe_read_fd = undef;
2413
}
2414
2487
7393
@output_fds_accum = ();
2415
2487
3116
for my $op ( @{ $kid->{OPS} } ) {
2487
13316
2416
2417
# next if $op->{IS_DEBUG};
2418
4515
6418
my $ok = eval {
2419
4515
100
100
31706
if ( $op->{TYPE} eq '<' ) {
100
100
100
100
100
100
50
2420
1262
3191
my $source = $op->{SOURCE};
2421
1262
100
100
16791
if ( !ref $source ) {
100
100
100
2422
_debug(
2423
"kid ", $kid->{NUM}, " to read ", $op->{KFD},
2424
83
50
1189
" from '" . $source, "' (read only)"
2425
) if _debugging_details;
2426
croak "simulated open failure"
2427
83
100
1787
if $self->{_simulate_open_failure};
2428
73
526
$op->{TFD} = _sysopen( $source, O_RDONLY );
2429
51
129
push @close_on_fail, $op->{TFD};
2430
}
2431
elsif (UNIVERSAL::isa( $source, 'GLOB' )
2432
|| UNIVERSAL::isa( $source, 'IO::Handle' ) ) {
2433
66
50
462
croak "Unopened filehandle in input redirect for $op->{KFD}"
2434
unless defined fileno $source;
2435
66
498
$op->{TFD} = fileno $source;
2436
_debug(
2437
"kid ", $kid->{NUM}, " to read ", $op->{KFD},
2438
" from fd ", $op->{TFD}
2439
66
50
1054
) if _debugging_details;
2440
}
2441
elsif ( UNIVERSAL::isa( $source, 'SCALAR' ) ) {
2442
_debug(
2443
"kid ", $kid->{NUM}, " to read ", $op->{KFD},
2444
1032
50
21787
" from SCALAR"
2445
) if _debugging_details;
2446
2447
1032
4529
$op->open_pipe( $self->_debug_fd );
2448
1032
4215
push @close_on_fail, $op->{KFD}, $op->{FD};
2449
2450
1032
2319
my $s = '';
2451
1032
2779
$op->{KIN_REF} = \$s;
2452
}
2453
elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
2454
71
50
1284
_debug( 'kid ', $kid->{NUM}, ' to read ', $op->{KFD}, ' from CODE' ) if _debugging_details;
2455
2456
71
464
$op->open_pipe( $self->_debug_fd );
2457
71
376
push @close_on_fail, $op->{KFD}, $op->{FD};
2458
2459
71
209
my $s = '';
2460
71
213
$op->{KIN_REF} = \$s;
2461
}
2462
else {
2463
10
2950
croak( "'" . ref($source) . "' not allowed as a source for input redirection" );
2464
}
2465
1220
4833
$op->_init_filters;
2466
}
2467
elsif ( $op->{TYPE} eq '{TYPE} eq '
2468
_debug(
2469
'kid to read ', $op->{KFD},
2470
98
50
1410
' from a pipe IPC::Run opens and returns',
2471
) if _debugging_details;
2472
2473
98
468
my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{SOURCE} );
2474
0
0
_debug "caller will write to ", fileno( ref $op->{SOURCE} eq 'SCALAR' ? ${ $op->{SOURCE} } : $op->{SOURCE} )
2475
98
0
1707
if _debugging_details;
50
2476
2477
98
199
$op->{TFD} = $r;
2478
98
330
$op->{FD} = undef; # we don't manage this fd
2479
98
495
$op->_init_filters;
2480
}
2481
elsif ( $op->{TYPE} eq '
2482
_debug(
2483
14
50
281
'kid to read ', $op->{KFD}, " from pty '", $op->{PTY_ID}, "'",
2484
) if _debugging_details;
2485
2486
14
53
for my $source ( $op->{SOURCE} ) {
2487
14
50
47
if ( UNIVERSAL::isa( $source, 'SCALAR' ) ) {
0
2488
_debug(
2489
"kid ", $kid->{NUM}, " to read ", $op->{KFD},
2490
14
50
251
" from SCALAR via pty '", $op->{PTY_ID}, "'"
2491
) if _debugging_details;
2492
2493
14
43
my $s = '';
2494
14
70
$op->{KIN_REF} = \$s;
2495
}
2496
elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
2497
_debug(
2498
"kid ", $kid->{NUM}, " to read ", $op->{KFD},
2499
0
0
0
" from CODE via pty '", $op->{PTY_ID}, "'"
2500
) if _debugging_details;
2501
0
0
my $s = '';
2502
0
0
$op->{KIN_REF} = \$s;
2503
}
2504
else {
2505
0
0
croak( "'" . ref($source) . "' not allowed as a source for '
2506
}
2507
}
2508
14
78
$op->{FD} = $self->{PTYS}->{ $op->{PTY_ID} }->fileno;
2509
13
93
$op->{TFD} = undef; # The fd isn't known until after fork().
2510
13
57
$op->_init_filters;
2511
}
2512
elsif ( $op->{TYPE} eq '>' ) {
2513
## N> output redirection.
2514
2728
7107
my $dest = $op->{DEST};
2515
2728
100
12753
if ( !ref $dest ) {
100
100
100
2516
_debug(
2517
"kid ", $kid->{NUM}, " to write ", $op->{KFD},
2518
" to '", $dest, "' (write only, create, ",
2519
201
0
3383
( $op->{TRUNC} ? 'truncate' : 'append' ),
50
2520
")"
2521
) if _debugging_details;
2522
croak "simulated open failure"
2523
201
100
1850
if $self->{_simulate_open_failure};
2524
$op->{TFD} = _sysopen(
2525
$dest,
2526
191
100
1604
( O_WRONLY | O_CREAT | ( $op->{TRUNC} ? O_TRUNC : O_APPEND ) )
2527
);
2528
191
50
724
if (Win32_MODE) {
2529
## I have no idea why this is needed to make the current
2530
## file position survive the gyrations TFD must go
2531
## through...
2532
0
0
POSIX::lseek( $op->{TFD}, 0, POSIX::SEEK_END() );
2533
}
2534
191
624
push @close_on_fail, $op->{TFD};
2535
}
2536
elsif ( UNIVERSAL::isa( $dest, 'GLOB' ) ) {
2537
60
50
356
croak("Unopened filehandle in output redirect, command $kid->{NUM}") unless defined fileno $dest;
2538
## Turn on autoflush, mostly just to flush out
2539
## existing output.
2540
60
298
my $old_fh = select($dest);
2541
60
1804
$| = 1;
2542
60
470
select($old_fh);
2543
60
207
$op->{TFD} = fileno $dest;
2544
60
50
1260
_debug( 'kid to write ', $op->{KFD}, ' to handle ', $op->{TFD} ) if _debugging_details;
2545
}
2546
elsif ( UNIVERSAL::isa( $dest, 'SCALAR' ) ) {
2547
2341
50
44845
_debug( "kid ", $kid->{NUM}, " to write $op->{KFD} to SCALAR" ) if _debugging_details;
2548
2549
2341
7202
$op->open_pipe( $self->_debug_fd );
2550
2341
6247
push @close_on_fail, $op->{FD}, $op->{TFD};
2551
2341
50
25661
$$dest = '' if $op->{TRUNC};
2552
}
2553
elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
2554
116
50
2419
_debug("kid $kid->{NUM} to write $op->{KFD} to CODE") if _debugging_details;
2555
2556
116
396
$op->open_pipe( $self->_debug_fd );
2557
116
288
push @close_on_fail, $op->{FD}, $op->{TFD};
2558
}
2559
else {
2560
10
1610
croak( "'" . ref($dest) . "' not allowed as a sink for output redirection" );
2561
}
2562
2708
5711
$output_fds_accum[ $op->{KFD} ] = $op;
2563
2708
6795
$op->_init_filters;
2564
}
2565
2566
elsif ( $op->{TYPE} eq '>pipe' ) {
2567
## N> output redirection to a pipe we open, but don't select()
2568
## on.
2569
_debug(
2570
"kid ", $kid->{NUM}, " to write ", $op->{KFD},
2571
61
50
1163
' to a pipe IPC::Run opens and returns'
2572
) if _debugging_details;
2573
2574
61
247
my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{DEST} );
2575
0
0
_debug "caller will read from ", fileno( ref $op->{DEST} eq 'SCALAR' ? ${ $op->{DEST} } : $op->{DEST} )
2576
61
0
1046
if _debugging_details;
50
2577
2578
61
179
$op->{TFD} = $w;
2579
61
181
$op->{FD} = undef; # we don't manage this fd
2580
61
303
$op->_init_filters;
2581
2582
61
153
$output_fds_accum[ $op->{KFD} ] = $op;
2583
}
2584
elsif ( $op->{TYPE} eq '>pty>' ) {
2585
27
107
my $dest = $op->{DEST};
2586
27
50
86
if ( UNIVERSAL::isa( $dest, 'SCALAR' ) ) {
0
2587
_debug(
2588
"kid ", $kid->{NUM}, " to write ", $op->{KFD},
2589
27
50
509
" to SCALAR via pty '", $op->{PTY_ID}, "'"
2590
) if _debugging_details;
2591
2592
27
50
161
$$dest = '' if $op->{TRUNC};
2593
}
2594
elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
2595
_debug(
2596
"kid ", $kid->{NUM}, " to write ", $op->{KFD},
2597
0
0
0
" to CODE via pty '", $op->{PTY_ID}, "'"
2598
) if _debugging_details;
2599
}
2600
else {
2601
0
0
croak( "'" . ref($dest) . "' not allowed as a sink for output redirection" );
2602
}
2603
2604
27
207
$op->{FD} = $self->{PTYS}->{ $op->{PTY_ID} }->fileno;
2605
27
155
$op->{TFD} = undef; # The fd isn't known until after fork().
2606
27
53
$output_fds_accum[ $op->{KFD} ] = $op;
2607
27
84
$op->_init_filters;
2608
}
2609
elsif ( $op->{TYPE} eq '|' ) {
2610
23
50
503
_debug( "pipelining $kid->{NUM} and " . ( $kid->{NUM} + 1 ) ) if _debugging_details;
2611
23
279
( $pipe_read_fd, $op->{TFD} ) = _pipe;
2612
23
50
183
if (Win32_MODE) {
2613
0
0
_dont_inherit($pipe_read_fd);
2614
0
0
_dont_inherit( $op->{TFD} );
2615
}
2616
23
74
@output_fds_accum = ();
2617
}
2618
elsif ( $op->{TYPE} eq '&' ) {
2619
0
0
@output_fds_accum = ();
2620
} # end if $op->{TYPE} tree
2621
4452
8091
1;
2622
}; # end eval
2623
4515
100
11819
unless ($ok) {
2624
63
226
push @errs, $@;
2625
63
50
1519
_debug 'caught ', $@ if _debugging;
2626
}
2627
} # end for ( OPS }
2628
}
2629
2630
2432
100
6381
if (@errs) {
2631
63
168
for (@close_on_fail) {
2632
26
119
_close($_);
2633
26
71
$_ = undef;
2634
}
2635
63
95
for ( keys %{ $self->{PTYS} } ) {
63
215
2636
1
50
3
next unless $self->{PTYS}->{$_};
2637
0
0
close $self->{PTYS}->{$_};
2638
0
0
$self->{PTYS}->{$_} = undef;
2639
}
2640
63
599
die join( '', @errs );
2641
}
2642
2643
## give all but the last child all of the output file descriptors
2644
## These will be reopened (and thus rendered useless) if the child
2645
## dup2s on to these descriptors, since we unshift these. This way
2646
## each process emits output to the same file descriptors that the
2647
## last child will write to. This is probably not quite correct,
2648
## since each child should write to the file descriptors inherited
2649
## from the parent.
2650
## TODO: fix the inheritance of output file descriptors.
2651
## NOTE: This sharing of OPS among kids means that we can't easily put
2652
## a kid number in each OPS structure to ping the kid when all ops
2653
## have closed (when $self->{PIPES} has emptied). This means that we
2654
## need to scan the KIDS whenever @{$self->{PIPES}} is empty to see
2655
## if there any of them are still alive.
2656
2369
11302
for ( my $num = 0; $num < $#{ $self->{KIDS} }; ++$num ) {
2426
8159
2657
57
399
for ( reverse @output_fds_accum ) {
2658
86
100
2726
next unless defined $_;
2659
_debug(
2660
'kid ', $self->{KIDS}->[$num]->{NUM}, ' also to write ', $_->{KFD},
2661
' to ', ref $_->{DEST}
2662
56
50
838
) if _debugging_details;
2663
56
104
unshift @{ $self->{KIDS}->[$num]->{OPS} }, $_;
56
156
2664
}
2665
}
2666
2667
## Open the debug pipe if we need it
2668
## Create the list of PIPES we need to scan and the bit vectors needed by
2669
## select(). Do this first so that _cleanup can _clobber() them if an
2670
## exception occurs.
2671
2369
4549
@{ $self->{PIPES} } = ();
2369
4300
2672
2369
5858
$self->{RIN} = '';
2673
2369
8098
$self->{WIN} = '';
2674
2369
4952
$self->{EIN} = '';
2675
## PIN is a vec()tor that indicates who's paused.
2676
2369
6565
$self->{PIN} = '';
2677
2369
3573
for my $kid ( @{ $self->{KIDS} } ) {
2369
6925
2678
2424
3275
for ( @{ $kid->{OPS} } ) {
2424
5250
2679
4484
100
9993
if ( defined $_->{FD} ) {
2680
_debug(
2681
'kid ', $kid->{NUM}, '[', $kid->{PID}, "]'s ", $_->{KFD},
2682
' is my ', $_->{FD}
2683
3654
50
60373
) if _debugging_details;
2684
3654
100
17480
vec( $self->{ $_->{TYPE} =~ /^ ? 'WIN' : 'RIN' }, $_->{FD}, 1 ) = 1;
2685
2686
# vec( $self->{EIN}, $_->{FD}, 1 ) = 1;
2687
3654
5293
push @{ $self->{PIPES} }, $_;
3654
7731
2688
}
2689
}
2690
}
2691
2692
2369
3073
for my $io ( @{ $self->{IOS} } ) {
2369
5833
2693
2
13
my $fd = $io->fileno;
2694
2
100
6
vec( $self->{RIN}, $fd, 1 ) = 1 if $io->mode =~ /r/;
2695
2
100
6
vec( $self->{WIN}, $fd, 1 ) = 1 if $io->mode =~ /w/;
2696
2697
# vec( $self->{EIN}, $fd, 1 ) = 1;
2698
2
4
push @{ $self->{PIPES} }, $io;
2
6
2699
}
2700
2701
## Put filters on the end of the filter chains to read & write the pipes.
2702
## Clear pipe states
2703
2369
3664
for my $pipe ( @{ $self->{PIPES} } ) {
2369
6382
2704
3656
9127
$pipe->{SOURCE_EMPTY} = 0;
2705
3656
8704
$pipe->{PAUSED} = 0;
2706
3656
100
10040
if ( $pipe->{TYPE} =~ /^>/ ) {
2707
my $pipe_reader = sub {
2708
4192
4192
13493
my ( undef, $out_ref ) = @_;
2709
2710
4192
50
11563
return undef unless defined $pipe->{FD};
2711
4192
50
15234
return 0 unless vec( $self->{ROUT}, $pipe->{FD}, 1 );
2712
2713
4192
15603
vec( $self->{ROUT}, $pipe->{FD}, 1 ) = 0;
2714
2715
4192
50
92097
_debug_desc_fd( 'reading from', $pipe ) if _debugging_details;
2716
4192
6244
my $in = eval { _read( $pipe->{FD} ) };
4192
12940
2717
4192
100
10910
if ($@) {
2718
21
84
$in = '';
2719
## IO::Pty throws the Input/output error if the kid dies.
2720
## read() throws the bad file descriptor message if the
2721
## kid dies on Win32.
2722
21
0
0
853
die $@
33
0
0
2723
unless $@ =~ $_EIO
2724
|| ( $@ =~ /input or output/ && $^O =~ /aix/ )
2725
|| ( Win32_MODE && $@ =~ /Bad file descriptor/ );
2726
}
2727
2728
4192
100
11578
unless ( length $in ) {
2729
2242
14174
$self->_clobber($pipe);
2730
2242
6376
return undef;
2731
}
2732
2733
## Protect the position so /.../g matches may be used.
2734
1950
4771
my $pos = pos $$out_ref;
2735
1950
16457
$$out_ref .= $in;
2736
1950
6618
pos($$out_ref) = $pos;
2737
1950
7300
return 1;
2738
2539
12832
};
2739
## Input filters are the last filters
2740
2539
3440
push @{ $pipe->{FILTERS} }, $pipe_reader;
2539
4200
2741
2539
3276
push @{ $self->{TEMP_FILTERS} }, $pipe_reader;
2539
7482
2742
}
2743
else {
2744
my $pipe_writer = sub {
2745
3181
3181
6647
my ( $in_ref, $out_ref ) = @_;
2746
3181
50
7568
return undef unless defined $pipe->{FD};
2747
return 0
2748
unless vec( $self->{WOUT}, $pipe->{FD}, 1 )
2749
3181
50
66
12540
|| $pipe->{PAUSED};
2750
2751
3181
15612
vec( $self->{WOUT}, $pipe->{FD}, 1 ) = 0;
2752
2753
3181
100
9624
if ( !length $$in_ref ) {
2754
3167
100
9694
if ( !defined get_more_input ) {
2755
706
5852
$self->_clobber($pipe);
2756
706
2457
return undef;
2757
}
2758
}
2759
2760
2475
100
5242
unless ( length $$in_ref ) {
2761
1574
100
3740
unless ( $pipe->{PAUSED} ) {
2762
85
50
3213
_debug_desc_fd( 'pausing', $pipe ) if _debugging_details;
2763
85
484
vec( $self->{WIN}, $pipe->{FD}, 1 ) = 0;
2764
2765
# vec( $self->{EIN}, $pipe->{FD}, 1 ) = 0;
2766
85
573
vec( $self->{PIN}, $pipe->{FD}, 1 ) = 1;
2767
85
276
$pipe->{PAUSED} = 1;
2768
}
2769
1574
3479
return 0;
2770
}
2771
901
50
23412
_debug_desc_fd( 'writing to', $pipe ) if _debugging_details;
2772
2773
901
50
2322
if ( length $$in_ref ) {
2774
901
6336
my $c = _write( $pipe->{FD}, $$in_ref );
2775
901
100
2553
unless ( defined $c ) {
2776
## EPIPE: child closed stdin before reading all input.
2777
## Treat this exactly like EOF on the pipe.
2778
231
50
5006
_debug_desc_fd( 'broken pipe writing to', $pipe )
2779
if _debugging_details;
2780
231
1622
$self->_clobber($pipe);
2781
231
700
return undef;
2782
}
2783
670
7167
substr( $$in_ref, 0, $c, '' );
2784
}
2785
else {
2786
0
0
$self->_clobber($pipe);
2787
0
0
return undef;
2788
}
2789
2790
670
1932
return 1;
2791
1117
11677
};
2792
## Output filters are the first filters
2793
1117
2038
unshift @{ $pipe->{FILTERS} }, $pipe_writer;
1117
2618
2794
1117
1443
push @{ $self->{TEMP_FILTERS} }, $pipe_writer;
1117
3716
2795
}
2796
}
2797
}
2798
2799
sub _dup2_gently {
2800
## A METHOD, NOT A FUNCTION, NEEDS $self!
2801
365
365
2458
my IPC::Run $self = shift;
2802
365
2099
my ( $files, $fd1, $fd2 ) = @_;
2803
## Moves TFDs that are using the destination fd out of the
2804
## way before calling _dup2
2805
365
1529
for (@$files) {
2806
970
100
3590
next unless defined $_->{TFD};
2807
919
100
5095
$_->{TFD} = _dup( $_->{TFD} ) if $_->{TFD} == $fd2;
2808
}
2809
365
50
33
5609
if ( defined $self->{DEBUG_FD} && $self->{DEBUG_FD} == $fd2 ) {
2810
0
0
$self->{DEBUG_FD} = _dup $self->{DEBUG_FD};
2811
0
0
$fds{$self->{DEBUG_FD}}{needed} = 1;
2812
}
2813
365
3572
_dup2_rudely( $fd1, $fd2 );
2814
}
2815
2816
=pod
2817
2818
=item close_terminal
2819
2820
This is used as (or in) an init sub to cast off the bonds of a controlling
2821
terminal. It must precede all other redirection ops that affect
2822
STDIN, STDOUT, or STDERR to be guaranteed effective.
2823
2824
=cut
2825
2826
sub close_terminal {
2827
## Cast of the bonds of a controlling terminal
2828
2829
# Just in case the parent (I'm talking to you FCGI) had these tied.
2830
7
7
1
20
untie *STDIN;
2831
7
71
untie *STDOUT;
2832
7
144
untie *STDERR;
2833
2834
7
50
282
POSIX::setsid() || croak "POSIX::setsid() failed";
2835
7
50
417
_debug "closing stdin, out, err"
2836
if _debugging_details;
2837
7
85
close STDIN;
2838
7
32
close STDERR;
2839
7
52
close STDOUT;
2840
}
2841
2842
sub _do_kid_and_exit {
2843
186
186
7715
my IPC::Run $self = shift;
2844
186
3987
my ($kid) = @_;
2845
2846
186
4016
my ( $s1, $s2 );
2847
186
50
7486
if ( $] < 5.008 ) {
2848
## For unknown reasons, placing these two statements in the eval{}
2849
## causes the eval {} to not catch errors after they are executed in
2850
## perl 5.6.0, godforsaken version that it is...not sure about 5.6.1.
2851
## Part of this could be that these symbols get destructed when
2852
## exiting the eval, and that destruction might be what's (wrongly)
2853
## confusing the eval{}, allowing the exception to propagate.
2854
0
0
$s1 = Symbol::gensym();
2855
0
0
$s2 = Symbol::gensym();
2856
}
2857
2858
186
4207
eval {
2859
186
4686
local $cur_self = $self;
2860
2861
## Suppress "Filehandle STDIN reopened as ... only for output" warnings.
2862
## In the child process, we intentionally reuse fd 0/1/2 after
2863
## close_terminal() frees them. This is expected during pty setup
2864
## and should not warn even when the parent has $^W=1.
2865
186
13656
local $^W = 0;
2866
2867
186
50
37999
if (_debugging) {
2868
_set_child_debug_name(
2869
ref $kid->{VAL} eq "CODE"
2870
? "CODE"
2871
0
0
0
: basename( $kid->{VAL}->[0] )
2872
);
2873
}
2874
2875
## close parent FD's first so they're out of the way.
2876
## Don't close STDIN, STDOUT, STDERR: they should be inherited or
2877
## overwritten below.
2878
146
16192
do { $_->{needed} = 1 for @fds{0..2} }
2879
186
100
5024
unless $self->{noinherit};
2880
2881
186
3312
$fds{$self->{SYNC_WRITER_FD}}{needed} = 1;
2882
186
100
4892
$fds{$self->{CODEREF_ERR_FD}}{needed} = 1 if defined $self->{CODEREF_ERR_FD};
2883
186
50
4150
$fds{$self->{DEBUG_FD}}{needed} = 1 if defined $self->{DEBUG_FD};
2884
2885
$fds{$_->{TFD}}{needed} = 1
2886
186
1567
foreach grep { defined $_->{TFD} } @{$kid->{OPS} };
374
7701
186
4847
2887
2888
2889
## TODO: use the forthcoming IO::Pty to close the terminal and
2890
## make the first pty for this child the controlling terminal.
2891
## This will also make it so that pty-laden kids don't cause
2892
## other kids to lose stdin/stdout/stderr.
2893
2894
186
100
1549
if ( %{ $self->{PTYS} } ) {
186
3828
2895
## Clean up the parent's fds.
2896
7
17
for ( keys %{ $self->{PTYS} } ) {
7
191
2897
7
50
330
_debug "Cleaning up parent's ptty '$_'" if _debugging_details;
2898
7
412
$self->{PTYS}->{$_}->make_slave_controlling_terminal;
2899
7
8500
my $slave = $self->{PTYS}->{$_}->slave;
2900
7
253
delete $fds{$self->{PTYS}->{$_}->fileno};
2901
7
391
close $self->{PTYS}->{$_};
2902
7
101
$self->{PTYS}->{$_} = $slave;
2903
}
2904
2905
7
561
close_terminal;
2906
7
97
delete @fds{0..2};
2907
}
2908
2909
186
1876
for my $sibling ( @{ $self->{KIDS} } ) {
186
5330
2910
208
1530
for ( @{ $sibling->{OPS} } ) {
208
1414
2911
405
100
4615
if ( $_->{TYPE} =~ /^.pty.$/ ) {
2912
8
157
$_->{TFD} = $self->{PTYS}->{ $_->{PTY_ID} }->fileno;
2913
8
119
$fds{$_->{TFD}}{needed} = 1;
2914
}
2915
2916
}
2917
}
2918
2919
## This is crude: we have no way of keeping track of browsing all open
2920
## fds, so we scan to a fairly high fd.
2921
186
50
8876
_debug "open fds: ", join " ", keys %fds if _debugging_details;
2922
2923
186
12091
_close( $_ ) foreach grep { ! $fds{$_}{needed} } keys %fds;
1532
7258
2924
2925
186
100
3916
if ( $kid->{ENV} ) {
2926
3
7
foreach my $k ( keys %{ $kid->{ENV} } ) {
3
35
2927
3
424
$ENV{$k} = $kid->{ENV}{$k};
2928
}
2929
}
2930
2931
186
2248
for ( @{ $kid->{OPS} } ) {
186
1399
2932
374
100
3691
if ( defined $_->{TFD} ) {
100
100
50
2933
2934
# we're always creating KFD
2935
353
2926
$fds{$_->{KFD}}{needed} = 1;
2936
2937
353
100
2558
unless ( $_->{TFD} == $_->{KFD} ) {
2938
352
5440
$self->_dup2_gently( $kid->{OPS}, $_->{TFD}, $_->{KFD} );
2939
352
3656
$fds{$_->{TFD}}{lazy_close} = 1;
2940
} else {
2941
1
6
my $fd = _dup($_->{TFD});
2942
1
3
$_->{TFD} = $fd;
2943
1
26
$self->_dup2_gently( $kid->{OPS}, $fd, $_->{KFD} );
2944
1
4
_close($fd);
2945
}
2946
}
2947
elsif ( $_->{TYPE} eq 'dup' ) {
2948
$self->_dup2_gently( $kid->{OPS}, $_->{KFD1}, $_->{KFD2} )
2949
12
50
203
unless $_->{KFD1} == $_->{KFD2};
2950
12
112
$fds{$_->{KFD2}}{needed} = 1;
2951
}
2952
elsif ( $_->{TYPE} eq 'close' ) {
2953
6
24
for ( $_->{KFD} ) {
2954
6
100
98
if ( $fds{$_} ) {
2955
5
68
_close($_);
2956
5
38
$_ = undef;
2957
}
2958
}
2959
}
2960
elsif ( $_->{TYPE} eq 'init' ) {
2961
3
121
$_->{SUB}->();
2962
}
2963
}
2964
2965
186
1063
_close( $_ ) foreach grep { $fds{$_}{lazy_close} } keys %fds;
1056
3198
2966
2967
186
100
4401
if ( ref $kid->{VAL} ne 'CODE' ) {
2968
183
50
39286
open $s1, ">&=$self->{SYNC_WRITER_FD}"
2969
or croak "$! setting filehandle to fd SYNC_WRITER_FD";
2970
183
1524
fcntl $s1, F_SETFD, 1;
2971
2972
183
50
2335
if ( defined $self->{DEBUG_FD} ) {
2973
0
0
0
open $s2, ">&=$self->{DEBUG_FD}"
2974
or croak "$! setting filehandle to fd DEBUG_FD";
2975
0
0
fcntl $s2, F_SETFD, 1;
2976
}
2977
2978
183
50
5383
if (_debugging) {
2979
0
0
my @cmd = ( $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ] );
0
0
0
0
2980
0
0
0
_debug 'execing ', join " ", map { /[\s\"]/ ? "'$_'" : $_ } @cmd;
0
0
2981
}
2982
2983
die "exec failed: simulating exec() failure"
2984
183
50
1129
if $self->{_simulate_exec_failure};
2985
2986
183
1185
_exec $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ];
183
4702
183
2470
2987
2988
0
0
croak "exec failed: $!";
2989
}
2990
};
2991
3
50
17
if ($@) {
2992
0
0
_write $self->{SYNC_WRITER_FD}, $@;
2993
## Avoid DESTROY.
2994
0
0
POSIX::_exit(1);
2995
}
2996
2997
## We must be executing code in the child, otherwise exec() would have
2998
## prevented us from being here.
2999
3
34
_close $self->{SYNC_WRITER_FD};
3000
3
50
61
_debug 'calling fork()ed CODE ref' if _debugging;
3001
3
50
33
POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
3002
## TODO: Overload CORE::GLOBAL::exit...
3003
## Wrap the coderef in eval so that a die() inside it does not propagate
3004
## out of _do_kid_and_exit and escape into the parent process's call stack.
3005
## Without this, the exception would unwind past the fork() point and cause
3006
## the child to continue executing parent code (GH#97).
3007
3
38
eval { $kid->{VAL}->() };
3
72
3008
0
0
my $kid_err = $@;
3009
3010
## There are bugs in perl closures up to and including 5.6.1
3011
## that may keep this next line from having any effect, and it
3012
## won't have any effect if our caller has kept a copy of it, but
3013
## this may cause the closure to be cleaned up. Maybe.
3014
0
0
$kid->{VAL} = undef;
3015
3016
## GH#122: Propagate the exception back to the parent via a dedicated
3017
## error pipe. We can't use the sync pipe because it must be closed
3018
## before running the CODE ref to avoid deadlocks (the parent blocks
3019
## on the sync pipe, so the child can't do I/O with the parent until
3020
## the sync pipe is closed).
3021
0
0
0
if ($kid_err) {
3022
0
0
0
if ( defined $self->{CODEREF_ERR_FD} ) {
3023
0
0
_write $self->{CODEREF_ERR_FD}, $kid_err;
3024
0
0
POSIX::close $self->{CODEREF_ERR_FD};
3025
}
3026
0
0
POSIX::_exit(1);
3027
}
3028
3029
POSIX::close $self->{CODEREF_ERR_FD}
3030
0
0
0
if defined $self->{CODEREF_ERR_FD};
3031
3032
## Use POSIX::_exit to avoid global destruction, since this might
3033
## cause DESTROY() to be called on objects created in the parent
3034
## and thus cause double cleanup. For instance, if DESTROY() unlinks
3035
## a file in the child, we don't want the parent to suddenly miss
3036
## it.
3037
0
0
POSIX::_exit(0);
3038
}
3039
3040
=pod
3041
3042
=item start
3043
3044
$h = start(
3045
\@cmd, \$in, \$out, ...,
3046
timeout( 30, name => "process timeout" ),
3047
$stall_timeout = timeout( 10, name => "stall timeout" ),
3048
);
3049
3050
$h = start \@cmd, '<', \$in, '|', \@cmd2, ...;
3051
3052
start() accepts a harness or harness specification and returns a harness
3053
after building all of the pipes and launching (via fork()/exec(), or, maybe
3054
someday, spawn()) all the child processes. It does not send or receive any
3055
data on the pipes, see pump() and finish() for that.
3056
3057
You may call harness() and then pass its result to start() if you like,
3058
but you only need to if it helps you structure or tune your application.
3059
If you do call harness(), you may skip start() and proceed directly to
3060
pump.
3061
3062
start() also starts all timers in the harness. See L
3063
for more information.
3064
3065
start() flushes STDOUT and STDERR to help you avoid duplicate output.
3066
It has no way of asking Perl to flush all your open filehandles, so
3067
you are going to need to flush any others you have open. Sorry.
3068
3069
Here's how if you don't want to alter the state of $| for your
3070
filehandle:
3071
3072
$ofh = select HANDLE; $of = $|; $| = 1; $| = $of; select $ofh;
3073
3074
If you don't mind leaving output unbuffered on HANDLE, you can do
3075
the slightly shorter
3076
3077
$ofh = select HANDLE; $| = 1; select $ofh;
3078
3079
Or, you can use IO::Handle's flush() method:
3080
3081
use IO::Handle;
3082
flush HANDLE;
3083
3084
Perl needs the equivalent of C's fflush( (FILE *)NULL ).
3085
3086
=cut
3087
3088
sub start {
3089
3090
# $SIG{__DIE__} = sub { my $s = shift; Carp::cluck $s; die $s };
3091
2548
2548
1
3849517
my $options;
3092
2548
50
33
31006
if ( @_ && ref $_[-1] eq 'HASH' ) {
3093
0
0
$options = pop;
3094
0
0
require Data::Dumper;
3095
0
0
carp "Passing in options as a hash is deprecated:\n", Data::Dumper::Dumper($options);
3096
}
3097
3098
2548
4572
my IPC::Run $self;
3099
2548
100
100
16927
if ( @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ ) ) {
3100
75
300
$self = shift;
3101
75
431
$self->{$_} = $options->{$_} for keys %$options;
3102
}
3103
else {
3104
2473
50
23023
$self = harness( @_, $options ? $options : () );
3105
}
3106
3107
2435
4366
local $cur_self = $self;
3108
3109
2435
100
6976
$self->kill_kill if $self->{STATE} == _started;
3110
3111
2435
50
50619
_debug "** starting" if _debugging;
3112
3113
2435
3657
$_->{RESULT} = undef for @{ $self->{KIDS} };
2435
8918
3114
3115
## Assume we're not being called from &run. It will correct our
3116
## assumption if need be. This affects whether &_select_loop clears
3117
## input queues to '' when they're empty.
3118
2435
6248
$self->{clear_ins} = 1;
3119
3120
2435
0
33
7507
IPC::Run::Win32Helper::optimize $self
3121
if Win32_MODE && $in_run;
3122
3123
2435
4598
my @errs;
3124
3125
2435
3428
for ( @{ $self->{TIMERS} } ) {
2435
5778
3126
404
791
eval { $_->start };
404
1861
3127
404
50
1201
if ($@) {
3128
0
0
push @errs, $@;
3129
0
0
0
_debug 'caught ', $@ if _debugging;
3130
}
3131
}
3132
3133
2435
3786
eval { $self->_open_pipes };
2435
17008
3134
2435
100
6397
if ($@) {
3135
66
199
push @errs, $@;
3136
66
50
1179
_debug 'caught ', $@ if _debugging;
3137
}
3138
3139
2435
100
5350
if ( !@errs ) {
3140
## This is a bit of a hack, we should do it for all open filehandles.
3141
## Since there's no way I know of to enumerate open filehandles, we
3142
## autoflush STDOUT and STDERR. This is done so that the children don't
3143
## inherit output buffers chock full o' redundant data. It's really
3144
## confusing to track that down.
3145
2369
13405
{ my $ofh = select STDOUT; my $of = $|; $| = 1; $| = $of; select $ofh; }
2369
10457
2369
4708
2369
3811
2369
8121
3146
2369
3527
{ my $ofh = select STDERR; my $of = $|; $| = 1; $| = $of; select $ofh; }
2369
3863
2369
8791
2369
4481
2369
3251
2369
3659
2369
7634
3147
2369
3118
for my $kid ( @{ $self->{KIDS} } ) {
2369
5036
3148
2413
5398
$kid->{RESULT} = undef;
3149
_debug "child: ", _debugstrings( $kid->{VAL} )
3150
2413
50
48979
if _debugging_details;
3151
2413
4268
eval {
3152
2413
100
5944
if ( $self->{_simulate_fork_failure} ) {
3153
10
70
$kid->{PID} = undef; # simulate fork() returning undef
3154
10
1590
croak "Cannot allocate memory during fork";
3155
}
3156
2403
50
7011
unless (Win32_MODE) {
3157
2403
10785
$self->_spawn($kid);
3158
}
3159
else {
3160
## TODO: Test and debug spawning code. Someday.
3161
_debug(
3162
'spawning ',
3163
_debugstrings(
3164
[
3165
$kid->{PATH},
3166
0
0
@{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ]
0
0
3167
]
3168
)
3169
0
0
0
0
) if $kid->{PATH} && _debugging;
3170
## The external kid wouldn't know what to do with it anyway.
3171
## This is only used by the "helper" pump processes on Win32.
3172
0
0
_dont_inherit( $self->{DEBUG_FD} );
3173
( $kid->{PID}, $kid->{PROCESS} ) = IPC::Run::Win32Helper::win32_spawn(
3174
ref( $kid->{VAL} ) eq "ARRAY"
3175
0
0
? [ $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ] ]
0
0
3176
: $kid->{VAL},
3177
$kid->{OPS},
3178
0
0
0
);
3179
0
0
0
_debug "spawn() = ", $kid->{PID} if _debugging;
3180
0
0
0
if ($self->{_sleep_after_win32_spawn}) {
3181
0
0
sleep $self->{_sleep_after_win32_spawn};
3182
0
0
0
_debug "after sleep $self->{_sleep_after_win32_spawn}"
3183
if _debugging;
3184
}
3185
}
3186
};
3187
2227
100
22085
if ($@) {
3188
12
51
push @errs, $@;
3189
12
50
261
_debug 'caught ', $@ if _debugging;
3190
}
3191
}
3192
}
3193
3194
## Close all those temporary filehandles that the kids needed.
3195
2249
5248
for my $pty ( values %{ $self->{PTYS} } ) {
2249
33742
3196
29
100
267
next unless $pty;
3197
28
564
close $pty->slave;
3198
}
3199
3200
2249
7310
my @closed;
3201
2249
4474
for my $kid ( @{ $self->{KIDS} } ) {
2249
9138
3202
2282
3562
for ( @{ $kid->{OPS} } ) {
2282
14847
3203
4168
10181
my $close_it = eval {
3204
defined $_->{TFD}
3205
&& !$_->{DONT_CLOSE}
3206
&& !$closed[ $_->{TFD} ]
3207
&& ( !Win32_MODE || !$_->{RECV_THROUGH_TEMP_FILE} ) ## Win32 hack
3208
4168
100
33
78826
};
100
66
3209
4168
50
11682
if ($@) {
3210
0
0
push @errs, $@;
3211
0
0
0
_debug 'caught ', $@ if _debugging;
3212
}
3213
4168
100
66
23319
if ( $close_it || $@ ) {
3214
3721
6225
eval {
3215
## GH#57: For plain '<' redirects with external Perl
3216
## handles, use close() on the handle so it is properly
3217
## invalidated (avoids stale-fd / double-close warnings).
3218
## Only for TYPE '<' — for '
3219
## is the *write* end that the caller uses; TFD is the
3220
## internal read end and must be closed via _close().
3221
3721
100
66
49184
if ( defined $_->{TYPE}
100
100
100
3222
&& $_->{TYPE} eq '<'
3223
&& ref $_->{SOURCE}
3224
&& ( UNIVERSAL::isa( $_->{SOURCE}, 'GLOB' )
3225
|| UNIVERSAL::isa( $_->{SOURCE}, 'IO::Handle' ) ) )
3226
{
3227
63
3225
close $_->{SOURCE};
3228
}
3229
else {
3230
3658
10729
_close( $_->{TFD} );
3231
}
3232
3721
16645
$closed[ $_->{TFD} ] = 1;
3233
3721
10060
$_->{TFD} = undef;
3234
};
3235
3721
50
13279
if ($@) {
3236
0
0
push @errs, $@;
3237
0
0
0
_debug 'caught ', $@ if _debugging;
3238
}
3239
}
3240
}
3241
}
3242
2249
50
10585
confess "gak!" unless defined $self->{PIPES};
3243
3244
2249
100
5688
if (@errs) {
3245
78
105
eval { $self->_cleanup };
78
301
3246
78
50
288
warn $@ if $@;
3247
78
490
die join( '', @errs );
3248
}
3249
3250
2171
7250
$self->{STATE} = _started;
3251
2171
41625
return $self;
3252
}
3253
3254
=item adopt
3255
3256
Experimental feature. NOT FUNCTIONAL YET, NEED TO CLOSE FDS BETTER IN CHILDREN. SEE t/adopt.t for a test suite.
3257
3258
=cut
3259
3260
sub adopt {
3261
1
1
1
671
my IPC::Run $self = shift;
3262
3263
1
2
for my $adoptee (@_) {
3264
1
1
push @{ $self->{IOS} }, @{ $adoptee->{IOS} };
1
3
1
2
3265
## NEED TO RENUMBER THE KIDS!!
3266
1
1
push @{ $self->{KIDS} }, @{ $adoptee->{KIDS} };
1
2
1
2
3267
1
2
push @{ $self->{PIPES} }, @{ $adoptee->{PIPES} };
1
1
1
2
3268
1
1
$self->{PTYS}->{$_} = $adoptee->{PTYS}->{$_} for keys %{ $adoptee->{PTYS} };
1
5
3269
1
2
push @{ $self->{TIMERS} }, @{ $adoptee->{TIMERS} };
1
3
1
1
3270
1
2
$adoptee->{STATE} = _finished;
3271
}
3272
}
3273
3274
sub _clobber {
3275
3265
3265
5666
my IPC::Run $self = shift;
3276
3265
5641
my ($file) = @_;
3277
3265
50
57163
_debug_desc_fd( "closing", $file ) if _debugging_details;
3278
3265
11628
my $doomed = $file->{FD};
3279
3265
100
29256
my $dir = $file->{TYPE} =~ /^ ? 'WIN' : 'RIN';
3280
3265
13146
vec( $self->{$dir}, $doomed, 1 ) = 0;
3281
3282
# vec( $self->{EIN}, $doomed, 1 ) = 0;
3283
3265
11462
vec( $self->{PIN}, $doomed, 1 ) = 0;
3284
3265
100
20839
if ( $file->{TYPE} =~ /^(.)pty.$/ ) {
50
3285
32
100
130
if ( $1 eq '>' ) {
3286
## Only close output ptys. This is so that ptys as inputs are
3287
## never autoclosed, which would risk losing data that was
3288
## in the slave->parent queue.
3289
21
50
537
_debug_desc_fd "closing pty", $file if _debugging_details;
3290
close $self->{PTYS}->{ $file->{PTY_ID} }
3291
21
50
1600
if defined $self->{PTYS}->{ $file->{PTY_ID} };
3292
21
225
$self->{PTYS}->{ $file->{PTY_ID} } = undef;
3293
}
3294
}
3295
elsif ( UNIVERSAL::isa( $file, 'IPC::Run::IO' ) ) {
3296
3233
50
23584
$file->close unless $file->{DONT_CLOSE};
3297
}
3298
else {
3299
0
0
_close($doomed);
3300
}
3301
3302
3265
9606
@{ $self->{PIPES} } = grep
3303
defined $_->{FD} && ( $_->{TYPE} ne $file->{TYPE} || $_->{FD} ne $doomed ),
3304
3265
100
6026
@{ $self->{PIPES} };
3265
30969
3305
3306
3265
6954
$file->{FD} = undef;
3307
}
3308
3309
sub _select_loop {
3310
3283
3283
4936
my IPC::Run $self = shift;
3311
3312
# With !defined $SIG{CHLD} (the default), Perl restarts any select() that
3313
# SIGCHLD interrupts. Install a no-op handler, to make select() terminate
3314
# with EINTR, accelerating our reaction. This doesn't help if SIGCHLD
3315
# arrives just before the select() call; https://cr.yp.to/docs/selfpipe.html
3316
# is a way to close that race condition. It doesn't help on Windows, where
3317
# we substitute a low timeout in zero-FD (timeout-only) select(). That
3318
# spends CPU to achieve responsiveness. We could do better there with a
3319
# C-language module that calls OpenProcess(), WSAEventSelect(), and
3320
# WaitForMultipleObjects().
3321
#
3322
# If non-IPC::Run code has installed a handler, via $SIG{CHLD} assignment or
3323
# via POSIX::sigaction(), this statement takes no action, and the existing
3324
# handler helps just like this one would. The cap on $not_forever helps
3325
# when non-IPC::Run code has blocked SIGCHLD, e.g. via POSIX::sigprocmask().
3326
# Override undef, '' and 'DEFAULT' — all of which leave the default
3327
# disposition in effect and would cause Perl to restart select().
3328
1278
local $SIG{CHLD} = sub { }
3329
3283
100
100
124299
unless $SIG{CHLD} && $SIG{CHLD} ne 'DEFAULT';
3330
3331
# When a child exits before consuming all of its stdin, any subsequent
3332
# write to the pipe raises SIGPIPE. With the default disposition that
3333
# kills the parent. Ignore SIGPIPE here so that POSIX::write() instead
3334
# returns -1 with errno EPIPE, which pipe_writer catches and handles by
3335
# closing the pipe gracefully. Honour an existing *custom* handler
3336
# installed by the caller, but override undef, '' and 'DEFAULT' — all
3337
# of which leave the default (fatal) disposition in effect.
3338
local $SIG{PIPE} = 'IGNORE'
3339
3283
100
100
40352
unless $SIG{PIPE} && $SIG{PIPE} ne 'DEFAULT';
3340
3341
3283
5201
my $io_occurred;
3342
3343
3283
4661
my $min_select_timeout = 0.01;
3344
3283
6511
my $not_forever = $min_select_timeout;
3345
3346
SELECT:
3347
3283
7676
while ( $self->pumpable ) {
3348
11193
100
100
43641
if ( $io_occurred && $self->{break_on_io} ) {
3349
401
50
9029
_debug "exiting _select(): io occurred and break_on_io set"
3350
if _debugging_details;
3351
401
1100
last;
3352
}
3353
3354
10792
100
34899
my $timeout = $self->{non_blocking} ? 0 : undef;
3355
3356
10792
100
15710
if ( @{ $self->{TIMERS} } ) {
10792
35422
3357
1764
3497
my $now = time;
3358
1764
2499
my $time_left;
3359
1764
3191
for ( @{ $self->{TIMERS} } ) {
1764
4708
3360
1764
50
13965
next unless $_->is_running;
3361
1764
10265
$time_left = $_->check($now);
3362
## Return when a timer expires
3363
1754
50
33
10675
return if defined $time_left && !$time_left;
3364
1754
100
66
8966
$timeout = $time_left
3365
if !defined $timeout || $time_left < $timeout;
3366
}
3367
}
3368
3369
##
3370
## See if we can unpause any input channels
3371
##
3372
10782
21284
my $paused = 0;
3373
3374
10782
16974
for my $file ( @{ $self->{PIPES} } ) {
10782
34036
3375
18914
100
66
54369
next unless $file->{PAUSED} && $file->{TYPE} =~ /^;
3376
3377
1558
50
31758
_debug_desc_fd( "checking for more input", $file ) if _debugging_details;
3378
1558
2190
my $did;
3379
1558
4595
1 while $did = $file->_do_filters($self);
3380
1558
50
66
7752
if ( defined $file->{FD} && !defined($did) || $did ) {
33
3381
0
0
0
_debug_desc_fd( "unpausing", $file ) if _debugging_details;
3382
0
0
$file->{PAUSED} = 0;
3383
0
0
vec( $self->{WIN}, $file->{FD}, 1 ) = 1;
3384
3385
# vec( $self->{EIN}, $file->{FD}, 1 ) = 1;
3386
0
0
vec( $self->{PIN}, $file->{FD}, 1 ) = 0;
3387
}
3388
else {
3389
## This gets incremented occasionally when the IO channel
3390
## was actually closed. That's a bug, but it seems mostly
3391
## harmless: it causes us to exit if break_on_io, or to set
3392
## the timeout to not be forever. I need to fix it, though.
3393
1558
2484
++$paused;
3394
}
3395
}
3396
3397
10782
50
266279
if (_debugging_details) {
3398
my $map = join(
3399
'',
3400
map {
3401
0
0
my $out;
0
0
3402
0
0
0
$out = 'r' if vec( $self->{RIN}, $_, 1 );
3403
0
0
0
$out = $out ? 'b' : 'w' if vec( $self->{WIN}, $_, 1 );
0
3404
0
0
0
0
$out = 'p' if !$out && vec( $self->{PIN}, $_, 1 );
3405
0
0
0
$out = $out ? uc($out) : 'x' if vec( $self->{EIN}, $_, 1 );
0
3406
0
0
0
$out = '-' unless $out;
3407
0
0
$out;
3408
} ( 0 .. 1024 )
3409
);
3410
0
0
$map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
3411
0
0
0
_debug 'fds for select: ', $map if _debugging_details;
3412
}
3413
3414
## _do_filters may have closed our last fd, and we need to see if
3415
## we have I/O, or are just waiting for children to exit.
3416
10782
24898
my $p = $self->pumpable;
3417
10782
50
29298
last unless $p;
3418
10782
100
100
65743
if ( $p != 0 && ( !defined $timeout || $timeout > 0.1 ) ) {
66
3419
## No I/O will wake the select loop up, but we have children
3420
## lingering, so we need to poll them with a short timeout.
3421
## Otherwise, assume more input will be coming.
3422
3423
9369
50
33
53260
if ( !Win32_MODE || $self->{RIN} || $self->{WIN} || $self->{EIN} ) {
0
0
3424
9369
18214
$timeout = $not_forever;
3425
9369
19699
$not_forever *= 2;
3426
9369
100
27408
$not_forever = 0.5 if $not_forever >= 0.5;
3427
}
3428
else {
3429
# see above rationale for Windows-specific behavior
3430
0
0
$timeout = $min_select_timeout;
3431
}
3432
}
3433
3434
## Make sure we don't block forever in select() because inputs are
3435
## paused.
3436
10782
0
33
32331
if ( !defined $timeout && !( @{ $self->{PIPES} } - $paused ) ) {
0
0
3437
## Need to return if we're in pump and all input is paused, or
3438
## we'll loop until all inputs are unpaused, which is darn near
3439
## forever. And a day.
3440
0
0
0
if ( $self->{break_on_io} ) {
3441
0
0
0
_debug "exiting _select(): no I/O to do and timeout=forever"
3442
if _debugging;
3443
0
0
last;
3444
}
3445
3446
## Otherwise, assume more input will be coming.
3447
0
0
0
0
if ( !Win32_MODE || $self->{RIN} || $self->{WIN} || $self->{EIN} ) {
0
0
3448
0
0
$timeout = $not_forever;
3449
0
0
$not_forever *= 2;
3450
0
0
0
$not_forever = 0.5 if $not_forever >= 0.5;
3451
}
3452
else {
3453
0
0
$timeout = $min_select_timeout;
3454
}
3455
}
3456
3457
10782
0
219047
_debug 'timeout=', defined $timeout ? $timeout : 'forever'
50
3458
if _debugging_details;
3459
3460
10782
22172
my $nfound;
3461
10782
50
28665
unless (Win32_MODE) {
3462
$nfound = select(
3463
$self->{ROUT} = $self->{RIN},
3464
$self->{WOUT} = $self->{WIN},
3465
$self->{EOUT} = $self->{EIN},
3466
10782
477828602
$timeout
3467
);
3468
}
3469
else {
3470
0
0
my @in = map $self->{$_}, qw( RIN WIN EIN );
3471
## Win32's select() on Win32 seems to die if passed vectors of
3472
## all 0's. Need to report this when I get back online.
3473
0
0
for (@in) {
3474
0
0
0
$_ = undef unless index( ( unpack "b*", $_ ), 1 ) >= 0;
3475
}
3476
3477
$nfound = select(
3478
$self->{ROUT} = $in[0],
3479
$self->{WOUT} = $in[1],
3480
0
0
$self->{EOUT} = $in[2],
3481
$timeout
3482
);
3483
3484
0
0
for ( $self->{ROUT}, $self->{WOUT}, $self->{EOUT} ) {
3485
0
0
0
$_ = "" unless defined $_;
3486
}
3487
}
3488
10782
100
100
187832
last if !$nfound && $self->{non_blocking};
3489
3490
9443
100
37436
if ( $nfound < 0 ) {
3491
125
50
4235
if ( $!{EINTR} ) {
3492
3493
# Caught a signal before any FD went ready. Ensure that
3494
# the bit fields reflect "no FDs ready".
3495
125
5282
$self->{ROUT} = $self->{WOUT} = $self->{EOUT} = '';
3496
125
547
$nfound = 0;
3497
}
3498
else {
3499
0
0
croak "$! in select";
3500
}
3501
}
3502
## TODO: Analyze the EINTR failure mode and see if this patch
3503
## is adequate and optimal.
3504
## TODO: Add an EINTR test to the test suite.
3505
3506
9443
50
642167
if (_debugging_details) {
3507
my $map = join(
3508
'',
3509
map {
3510
0
0
my $out;
0
0
3511
0
0
0
$out = 'r' if vec( $self->{ROUT}, $_, 1 );
3512
0
0
0
$out = $out ? 'b' : 'w' if vec( $self->{WOUT}, $_, 1 );
0
3513
0
0
0
$out = $out ? uc($out) : 'x' if vec( $self->{EOUT}, $_, 1 );
0
3514
0
0
0
$out = '-' unless $out;
3515
0
0
$out;
3516
} ( 0 .. 128 )
3517
);
3518
0
0
$map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
3519
0
0
_debug "selected ", $map;
3520
}
3521
3522
## Need to copy since _clobber alters @{$self->{PIPES}}.
3523
## TODO: Rethink _clobber(). Rethink $file->{PAUSED}, too.
3524
9443
18076
my @pipes = @{ $self->{PIPES} };
9443
56503
3525
9443
100
106548
$io_occurred = $_->poll($self) ? 1 : $io_occurred for @pipes;
3526
3527
}
3528
3529
3273
55485
return;
3530
}
3531
3532
sub _cleanup {
3533
2299
2299
6739
my IPC::Run $self = shift;
3534
2299
50
53841
_debug "cleaning up" if _debugging_details;
3535
3536
2299
4961
for ( values %{ $self->{PTYS} } ) {
2299
9233
3537
29
100
180
next unless ref $_;
3538
7
14
eval {
3539
7
50
98
_debug "closing slave fd ", fileno $_->slave if _debugging_data;
3540
7
49
close $_->slave;
3541
};
3542
7
50
119
carp $@ . " while closing ptys" if $@;
3543
7
14
eval {
3544
7
50
91
_debug "closing master fd ", fileno $_ if _debugging_data;
3545
7
350
close $_;
3546
};
3547
7
50
28
carp $@ . " closing ptys" if $@;
3548
}
3549
3550
2299
50
38733
_debug "cleaning up pipes" if _debugging_details;
3551
## _clobber modifies PIPES
3552
2299
4153
$self->_clobber( $self->{PIPES}->[0] ) while @{ $self->{PIPES} };
2343
7598
3553
3554
# reap kids
3555
2299
8176
my @coderef_exceptions;
3556
2299
6844
for my $kid ( @{ $self->{KIDS} } ) {
2299
14634
3557
2335
100
100
20311
if ( !defined $kid->{PID} || !length $kid->{PID} ) {
3558
76
50
1255
_debug 'never ran child ', $kid->{NUM}, ", can't reap"
3559
if _debugging;
3560
76
108
for my $op ( @{ $kid->{OPS} } ) {
76
209
3561
_close( $op->{TFD} )
3562
109
50
33
448
if defined $op->{TFD} && !defined $op->{TEMP_FILE_HANDLE};
3563
}
3564
}
3565
else {
3566
2259
9534
_waitpid( $kid, 0 );
3567
}
3568
3569
## GH#122: Read exception from CODE ref error pipe after the child
3570
## has exited. The pipe is guaranteed to have been closed by the
3571
## child's POSIX::_exit(), so _read() will not block.
3572
2335
100
8414
if ( defined $kid->{CODEREF_ERR_FD} ) {
3573
343
2247
my $err = _read $kid->{CODEREF_ERR_FD};
3574
343
7397
POSIX::close $kid->{CODEREF_ERR_FD};
3575
343
1129
delete $kid->{CODEREF_ERR_FD};
3576
343
100
66
4550
push @coderef_exceptions, $err if defined $err && length $err;
3577
}
3578
}
3579
2299
100
6162
$self->{CODEREF_EXCEPTIONS} = \@coderef_exceptions if @coderef_exceptions;
3580
3581
# OPS cleanup. Kids may share an OPS object; search for "also to write".
3582
# Example harness: run(['echo',1], '&', ['echo',2], '>', \$out). Hence,
3583
# this starts after the last reap.
3584
2299
3837
for my $kid ( @{ $self->{KIDS} } ) {
2299
7279
3585
3586
2335
50
47972
_debug "cleaning up filters at kid ", $kid->{NUM} if _debugging_details;
3587
2335
5869
for my $op ( @{ $kid->{OPS} } ) {
2335
6546
3588
4168
10653
@{ $op->{FILTERS} } = grep {
3589
4453
5610
my $filter = $_;
3590
4453
6201
!grep $filter == $_, @{ $self->{TEMP_FILTERS} };
4453
14697
3591
4168
5305
} @{ $op->{FILTERS} };
4168
10699
3592
}
3593
3594
2335
3572
for my $op ( @{ $kid->{OPS} } ) {
2335
4905
3595
4168
100
18825
$op->_cleanup($self) if UNIVERSAL::isa( $op, "IPC::Run::IO" );
3596
}
3597
}
3598
2299
5711
$self->{STATE} = _finished;
3599
2299
5722
@{ $self->{TEMP_FILTERS} } = ();
2299
55064
3600
2299
50
46882
_debug "done cleaning up" if _debugging_details;
3601
3602
2299
50
6742
POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
3603
2299
13732
$self->{DEBUG_FD} = undef;
3604
}
3605
3606
=pod
3607
3608
=item pump
3609
3610
pump $h;
3611
$h->pump;
3612
3613
Pump accepts a single parameter harness. It blocks until it delivers some
3614
input or receives some output. It returns TRUE if there is still input or
3615
output to be done, FALSE otherwise.
3616
3617
pump() will automatically call start() if need be, so you may call harness()
3618
then proceed to pump() if that helps you structure your application.
3619
3620
If pump() is called after all harnessed activities have completed, a "process
3621
ended prematurely" exception to be thrown. This allows for simple scripting
3622
of external applications without having to add lots of error handling code at
3623
each step of the script:
3624
3625
$h = harness \@smbclient, \$in, \$out, $err;
3626
3627
$in = "cd /foo\n";
3628
$h->pump until $out =~ /^smb.*> \Z/m;
3629
die "error cding to /foo:\n$out" if $out =~ "ERR";
3630
$out = '';
3631
3632
$in = "mget *\n";
3633
$h->pump until $out =~ /^smb.*> \Z/m;
3634
die "error retrieving files:\n$out" if $out =~ "ERR";
3635
3636
$h->finish;
3637
3638
warn $err if $err;
3639
3640
=cut
3641
3642
sub pump {
3643
1771
50
33
1771
1
128121
die "pump() takes only a single harness as a parameter"
3644
unless @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ );
3645
3646
1771
2664
my IPC::Run $self = shift;
3647
3648
1771
2979
local $cur_self = $self;
3649
3650
1771
50
37563
_debug "** pumping"
3651
if _debugging;
3652
3653
1771
50
4442
$self->start if $self->{STATE} < _started;
3654
1771
50
4020
croak "process ended prematurely" unless $self->pumpable;
3655
3656
1771
3216
$self->{auto_close_ins} = 0;
3657
1771
2649
$self->{break_on_io} = 1;
3658
1771
4449
$self->_select_loop;
3659
1762
3911
return $self->pumpable;
3660
}
3661
3662
=pod
3663
3664
=item pump_nb
3665
3666
pump_nb $h;
3667
$h->pump_nb;
3668
3669
"pump() non-blocking", pumps if anything's ready to be pumped, returns
3670
immediately otherwise. This is useful if you're doing some long-running
3671
task in the foreground, but don't want to starve any child processes.
3672
3673
=cut
3674
3675
sub pump_nb {
3676
1403
1403
1
7342
my IPC::Run $self = shift;
3677
3678
1403
1957
$self->{non_blocking} = 1;
3679
1403
1550
my $r = eval { $self->pump };
1403
2444
3680
1403
1858
$self->{non_blocking} = 0;
3681
1403
50
2075
die $@ if $@;
3682
1403
2788
return $r;
3683
}
3684
3685
=pod
3686
3687
=item close_stdin
3688
3689
$h->close_stdin;
3690
3691
Closes the input pipe(s) to the child process(es), signaling EOF on
3692
the child's STDIN. Does B wait for the child to finish or drain
3693
remaining output. After calling this, the caller can continue to
3694
C to retrieve output incrementally.
3695
3696
This is useful when streaming large amounts of data through a child
3697
process (e.g., decompression) where you want to signal end-of-input
3698
but continue draining output without buffering it all in memory:
3699
3700
my ( $in, $out ) = ( '', '' );
3701
my $h = start \@cmd, \$in, \$out, timeout( 30 );
3702
3703
while ( read_more_input_into( $in ) ) {
3704
$h->pump;
3705
process_output( $out ) if length $out;
3706
$out = '';
3707
}
3708
3709
$h->close_stdin;
3710
3711
while ( $h->pumpable ) {
3712
$h->pump;
3713
process_output( $out ) if length $out;
3714
$out = '';
3715
}
3716
3717
$h->finish;
3718
3719
B Always use a C with this pattern. Without one, the
3720
C calls can deadlock if the child blocks on writing output while
3721
you are blocked trying to write input (or vice versa).
3722
3723
Without C, calling C would accumulate all
3724
remaining output in C<$out> before returning, potentially exhausting
3725
memory for children that produce large output (like decompressors).
3726
3727
Returns the harness object for chaining.
3728
3729
=cut
3730
3731
sub close_stdin {
3732
48
48
1
608
my IPC::Run $self = shift;
3733
3734
48
261
local $cur_self = $self;
3735
3736
48
50
156
croak "harness has not been started" unless $self->{STATE} >= _started;
3737
3738
48
50
1283
_debug "** closing stdin" if _debugging;
3739
3740
# Match all input pipe types: '<' (plain), '
3741
# _clobber() handles each type appropriately: for regular pipes it
3742
# closes the fd (signaling EOF to the child); for input ptys it
3743
# removes them from the select vectors without closing the pty
3744
# master (consistent with _clobber's existing pty safety logic).
3745
48
82
for my $pipe ( @{ $self->{PIPES} } ) {
48
273
3746
50
100
279
next unless $pipe->{TYPE} =~ /^;
3747
42
339
$self->_clobber($pipe);
3748
}
3749
3750
48
155
return $self;
3751
}
3752
3753
=pod
3754
3755
=item started
3756
3757
Returns TRUE if the harness has been started and has not yet finished.
3758
This is useful when a harness may or may not have been started by the
3759
caller, and you want to conditionally start it:
3760
3761
$h->start unless $h->started;
3762
3763
=cut
3764
3765
sub started {
3766
13
13
1
76
my IPC::Run $self = shift;
3767
13
197
return $self->{STATE} >= _started;
3768
}
3769
3770
=item pumpable
3771
3772
Returns TRUE if calling pump() won't throw an immediate "process ended
3773
prematurely" exception. This means that there are open I/O channels or
3774
active processes. May yield the parent processes' time slice for 0.01
3775
second if all pipes are to the child and all are paused. In this case
3776
we can't tell if the child is dead, so we yield the processor and
3777
then attempt to reap the child in a nonblocking way.
3778
3779
To wait for child processes to exit during an event loop, poll
3780
C<$h->pumpable> until it returns false, then call C.
3781
See also L to test whether the harness has already been
3782
finished.
3783
3784
=cut
3785
3786
## Undocumented feature (don't depend on it outside this module):
3787
## returns -1 if we have I/O channels open, or >0 if no I/O channels
3788
## open, but we have kids running. This allows the select loop
3789
## to poll for child exit.
3790
sub pumpable {
3791
30231
30231
1
82798
my IPC::Run $self = shift;
3792
3793
## There's a catch-22 we can get in to if there is only one pipe left
3794
## open to the child and it's paused (ie the SCALAR it's tied to
3795
## is ''). It's paused, so we're not select()ing on it, so we don't
3796
## check it to see if the child attached to it is alive and it stays
3797
## in @{$self->{PIPES}} forever. So, if all pipes are paused, see if
3798
## we can reap the child.
3799
30231
100
36596
return -1 if grep !$_->{PAUSED}, @{ $self->{PIPES} };
30231
163811
3800
3801
## See if the child is dead.
3802
4433
16236
$self->reap_nb;
3803
4433
100
14901
return 0 unless $self->_running_kids;
3804
3805
## If we reap_nb and it's not dead yet, yield to it to see if it
3806
## exits.
3807
##
3808
## A better solution would be to unpause all the pipes, but I tried that
3809
## and it never errored on linux. Sigh.
3810
1320
255924
select undef, undef, undef, 0.0001;
3811
3812
## try again
3813
1320
7499
$self->reap_nb;
3814
1320
100
4300
return 0 unless $self->_running_kids;
3815
3816
1283
3428
return -1; ## There are pipes waiting
3817
}
3818
3819
sub _running_kids {
3820
5825
5825
8616
my IPC::Run $self = shift;
3821
return grep
3822
defined $_->{PID} && !defined $_->{RESULT},
3823
5825
66
7756
@{ $self->{KIDS} };
5825
40150
3824
}
3825
3826
=pod
3827
3828
=item reap_nb
3829
3830
Attempts to reap child processes, but does not block.
3831
3832
Does not currently take any parameters, one day it will allow specific
3833
children to be reaped.
3834
3835
Only call this from a signal handler if your C is recent enough
3836
to have safe signal handling (5.6.1 did not, IIRC, but it was being discussed
3837
on perl5-porters). Calling this (or doing any significant work) in a signal
3838
handler on older Cs is asking for seg faults.
3839
3840
=cut
3841
3842
my $still_runnings;
3843
3844
sub reap_nb {
3845
5825
5825
1
9571
my IPC::Run $self = shift;
3846
3847
5825
10806
local $cur_self = $self;
3848
3849
## No more pipes, look to see if all the kids yet live, reaping those
3850
## that haven't. I'd use $SIG{CHLD}/$SIG{CLD}, but that's broken
3851
## on older (SYSV) platforms and perhaps less portable than waitpid().
3852
## This could be slow with a lot of kids, but that's rare and, well,
3853
## a lot of kids is slow in the first place.
3854
## Oh, and this keeps us from reaping other children the process
3855
## may have spawned.
3856
5825
7034
for my $kid ( @{ $self->{KIDS} } ) {
5825
19878
3857
5876
14976
_waitpid( $kid, 1 );
3858
}
3859
}
3860
3861
# Support routine (non-method) for waitpid() or platform's equivalent. Sets $?
3862
# and $_[0]->{RESULT} iff the kid exited.
3863
sub _waitpid {
3864
8135
8135
18291
my ( $kid, $nohang ) = @_;
3865
3866
8135
50
22457
if (Win32_MODE) {
3867
0
0
require Win32::Process;
3868
3869
0
0
0
0
return if !defined $kid->{PROCESS} || defined $kid->{RESULT};
3870
0
0
0
my $wait_timeout = $nohang ? 0 : Win32::Process::INFINITE();
3871
0
0
0
unless ( $kid->{PROCESS}->Wait($wait_timeout) ) {
3872
0
0
0
confess "kid $kid->{PID} still running after indefinite wait"
3873
unless $nohang;
3874
0
0
0
_debug "kid $kid->{NUM} ($kid->{PID}) still running"
3875
if _debugging_details;
3876
0
0
return;
3877
}
3878
3879
0
0
0
_debug "kid $kid->{NUM} ($kid->{PID}) exited"
3880
if _debugging;
3881
3882
0
0
my $native_result;
3883
0
0
0
$kid->{PROCESS}->GetExitCode($native_result)
3884
or croak "$! while GetExitCode()ing for Win32 process";
3885
3886
0
0
0
unless ( defined $native_result ) {
3887
0
0
$kid->{RESULT} = "0 but true";
3888
0
0
$? = $kid->{RESULT} = 0x0F;
3889
}
3890
else {
3891
0
0
my $win32_full_result = $native_result << 8;
3892
0
0
0
if ( $win32_full_result >> 8 != $native_result ) {
3893
3894
# !USE_64_BIT_INT build and exit code > 0xFFFFFF
3895
0
0
require Math::BigInt;
3896
0
0
$win32_full_result = Math::BigInt->new($native_result);
3897
0
0
$win32_full_result->blsft(8);
3898
}
3899
0
0
$? = $kid->{RESULT} = $win32_full_result;
3900
}
3901
}
3902
else {
3903
8135
100
66
49460
return if !defined $kid->{PID} || defined $kid->{RESULT};
3904
4810
100
255347234
my $pid = waitpid $kid->{PID}, $nohang ? POSIX::WNOHANG() : 0;
3905
4810
100
21250
unless ($pid) {
3906
2612
50
5918
confess "kid $kid->{PID} still running after indefinite wait"
3907
unless $nohang;
3908
2612
50
77864
_debug "$kid->{NUM} ($kid->{PID}) still running"
3909
if _debugging_details;
3910
2612
6572
return;
3911
}
3912
3913
2198
100
7402
if ( $pid < 0 ) {
3914
2
50
49
_debug "No such process: $kid->{PID}\n" if _debugging;
3915
2
12
$kid->{RESULT} = "unknown result, unknown PID";
3916
}
3917
else {
3918
2196
50
79597
_debug "kid $kid->{NUM} ($kid->{PID}) exited"
3919
if _debugging;
3920
3921
confess "waitpid returned the wrong PID: $pid instead of $kid->{PID}"
3922
2196
50
10055
unless $pid == $kid->{PID};
3923
2196
50
38741
_debug "$kid->{PID} returned $?\n" if _debugging;
3924
2196
19802
$kid->{RESULT} = $?;
3925
}
3926
}
3927
}
3928
3929
=pod
3930
3931
=item finish
3932
3933
This must be called after the last start() or pump() call for a harness,
3934
or your system will accumulate defunct processes and you may "leak"
3935
file descriptors.
3936
3937
finish() returns TRUE if all children returned 0 (and were not signaled and did
3938
not coredump, ie ! $?), and FALSE otherwise (this is like run(), and the
3939
opposite of system()).
3940
3941
Once a harness has been finished, it may be run() or start()ed again,
3942
including by pump()s auto-start.
3943
3944
If this throws an exception rather than a normal exit, the harness may
3945
be left in an unstable state, it's best to kill the harness to get rid
3946
of all the child processes, etc.
3947
3948
Specifically, if a timeout expires in finish(), finish() will not
3949
kill all the children. Call C<< $h->kill_kill >> in this case if you care.
3950
This differs from the behavior of L.
3951
3952
=cut
3953
3954
sub finish {
3955
2159
2159
1
1588563
my IPC::Run $self = shift;
3956
2159
50
33
10492
my $options = @_ && ref $_[-1] eq 'HASH' ? pop : {};
3957
3958
2159
4816
local $cur_self = $self;
3959
3960
2159
50
53876
_debug "** finishing" if _debugging;
3961
3962
2159
10346
$self->{non_blocking} = 0;
3963
2159
14951
$self->{auto_close_ins} = 1;
3964
2159
14748
$self->{break_on_io} = 0;
3965
3966
# We don't alter $self->{clear_ins}, start() and run() control it.
3967
3968
2159
100
100
4582
if ( %{ $self->{PTYS} } || @{ $self->{PIPES} } || @{ $self->{TIMERS} } ) {
2159
100
25224
2131
21017
691
5663
3969
1534
16410
while ( $self->pumpable ) {
3970
1512
14301
$self->_select_loop($options);
3971
}
3972
}
3973
2158
27869
$self->_cleanup;
3974
3975
## GH#122: Propagate CODE ref exceptions to the caller.
3976
2158
100
66
8219
if ( $self->{CODEREF_EXCEPTIONS} && @{ $self->{CODEREF_EXCEPTIONS} } ) {
88
704
3977
88
35332
croak $self->{CODEREF_EXCEPTIONS}->[0];
3978
}
3979
3980
2070
17545
return !$self->full_result;
3981
}
3982
3983
=pod
3984
3985
=item result
3986
3987
$h->result;
3988
3989
Returns the first non-zero result code (ie $? >> 8). See L to
3990
get the $? value for a child process.
3991
3992
To get the result of a particular child, do:
3993
3994
$h->result( 0 ); # first child's $? >> 8
3995
$h->result( 1 ); # second child
3996
3997
or
3998
3999
($h->results)[0]
4000
($h->results)[1]
4001
4002
Returns undef if no child processes were spawned and no child number was
4003
specified. Throws an exception if an out-of-range child number is passed.
4004
4005
Note that C returns C both when no children have exited and
4006
when all children exited with a zero exit code. Use L to
4007
determine whether the harness has actually completed, or use L to
4008
get the exit codes of all children (including zeros).
4009
4010
=cut
4011
4012
sub _assert_finished {
4013
2104
2104
4171
my IPC::Run $self = $_[0];
4014
4015
2104
50
7413
croak "Harness not run" unless $self->{STATE} >= _finished;
4016
2104
50
5842
croak "Harness not finished running" unless $self->{STATE} == _finished;
4017
}
4018
4019
sub _child_result {
4020
19
19
29
my IPC::Run $self = shift;
4021
4022
19
34
my ($which) = @_;
4023
croak(
4024
"Only ",
4025
0
0
scalar( @{ $self->{KIDS} } ),
4026
" child processes, no process $which"
4027
19
50
33
73
) unless $which >= 0 && $which <= $#{ $self->{KIDS} };
19
67
4028
19
83
return $self->{KIDS}->[$which]->{RESULT};
4029
}
4030
4031
# When $SIG{CHLD} is 'IGNORE', waitpid returns -1 and RESULT is set to
4032
# the string "unknown result, unknown PID". Using that string in numeric
4033
# context (>> 8, 0+, boolean) triggers a warning. This helper silences it.
4034
sub _numeric_result {
4035
231
231
2246
no warnings 'numeric';
231
638
231
156673
4036
2138
2138
17733
return 0 + $_[0];
4037
}
4038
4039
sub result {
4040
15
15
1
4354
&_assert_finished;
4041
15
26
my IPC::Run $self = shift;
4042
4043
15
100
52
if (@_) {
4044
10
26
my ($which) = @_;
4045
10
26
return _numeric_result( $self->_child_result($which) ) >> 8;
4046
}
4047
else {
4048
5
50
19
return undef unless @{ $self->{KIDS} };
5
30
4049
5
14
for ( @{ $self->{KIDS} } ) {
5
20
4050
13
28
my $candidate = _numeric_result( $_->{RESULT} ) >> 8;
4051
13
100
87
return $candidate if $candidate;
4052
}
4053
}
4054
}
4055
4056
=pod
4057
4058
=item results
4059
4060
Returns a list of child exit values. See L if you want to
4061
know if a signal killed the child.
4062
4063
Throws an exception if the harness is not in a finished state.
4064
4065
=cut
4066
4067
sub results {
4068
4
4
1
908
&_assert_finished;
4069
4
12
my IPC::Run $self = shift;
4070
4071
4
6
return map { _numeric_result( $_->{RESULT} ) >> 8 } @{ $self->{KIDS} };
10
18
4
21
4072
}
4073
4074
=pod
4075
4076
=item full_result
4077
4078
$h->full_result;
4079
4080
Returns the first non-zero $?. See L to get the first $? >> 8
4081
value for a child process.
4082
4083
To get the result of a particular child, do:
4084
4085
$h->full_result( 0 ); # first child's $?
4086
$h->full_result( 1 ); # second child
4087
4088
or
4089
4090
($h->full_results)[0]
4091
($h->full_results)[1]
4092
4093
Returns undef if no child processes were spawned and no child number was
4094
specified. Throws an exception if an out-of-range child number is passed.
4095
4096
=cut
4097
4098
sub full_result {
4099
2082
2082
1
6612
&_assert_finished;
4100
4101
2082
2749
my IPC::Run $self = shift;
4102
4103
2082
100
5337
if (@_) {
4104
9
17
my ($which) = @_;
4105
9
25
return $self->_child_result($which);
4106
}
4107
else {
4108
2073
100
5119
return undef unless @{ $self->{KIDS} };
2073
6228
4109
2071
4581
for ( @{ $self->{KIDS} } ) {
2071
6173
4110
2105
100
14102
return $_->{RESULT} if _numeric_result( $_->{RESULT} );
4111
}
4112
}
4113
}
4114
4115
=pod
4116
4117
=item full_results
4118
4119
Returns a list of child exit values as returned by C. See L
4120
if you don't care about coredumps or signals.
4121
4122
Throws an exception if the harness is not in a finished state.
4123
4124
=cut
4125
4126
sub full_results {
4127
3
3
1
3245
&_assert_finished;
4128
3
5
my IPC::Run $self = shift;
4129
4130
3
50
11
croak "Harness not run" unless $self->{STATE} >= _finished;
4131
3
50
18
croak "Harness not finished running" unless $self->{STATE} == _finished;
4132
4133
3
8
return map $_->{RESULT}, @{ $self->{KIDS} };
3
23
4134
}
4135
4136
=pod
4137
4138
=item pid
4139
4140
$h->pid;
4141
4142
Returns the process ID of the first child process, or undef if no child
4143
processes have been spawned yet.
4144
4145
To get the PID of a particular child, do:
4146
4147
$h->pid( 0 ); # first child's PID
4148
$h->pid( 1 ); # second child's PID
4149
4150
or
4151
4152
($h->pids)[0]
4153
($h->pids)[1]
4154
4155
PIDs are available as soon as the harness has been started with L.
4156
4157
=cut
4158
4159
sub pid {
4160
28
28
1
9172
my IPC::Run $self = shift;
4161
4162
28
100
54
if (@_) {
4163
8
26
my ($which) = @_;
4164
croak(
4165
"Only ",
4166
0
0
scalar( @{ $self->{KIDS} } ),
4167
" child processes, no process $which"
4168
8
50
33
55
) unless $which >= 0 && $which <= $#{ $self->{KIDS} };
8
32
4169
8
50
60
return $self->{KIDS}->[$which]->{PID} || undef;
4170
}
4171
else {
4172
20
50
15
return undef unless @{ $self->{KIDS} };
20
75
4173
20
50
185
return $self->{KIDS}->[0]->{PID} || undef;
4174
}
4175
}
4176
4177
=pod
4178
4179
=item pids
4180
4181
Returns a list of child process IDs. See L to get the PID of a
4182
specific child process.
4183
4184
PIDs are available as soon as the harness has been started with L.
4185
4186
=cut
4187
4188
sub pids {
4189
8
8
1
64
my IPC::Run $self = shift;
4190
4191
8
50
8
return map { $_->{PID} || undef } @{ $self->{KIDS} };
11
76
8
27
4192
}
4193
4194
=pod
4195
4196
=item is_running
4197
4198
$h->is_running;
4199
4200
Returns true if the harness is currently running (i.e. after L and
4201
before L), false otherwise.
4202
4203
=cut
4204
4205
sub is_running {
4206
7
7
1
51
my IPC::Run $self = shift;
4207
4208
7
103
return $self->{STATE} == _started;
4209
}
4210
4211
=pod
4212
4213
=item full_path
4214
4215
$h->full_path;
4216
4217
Returns the full path to the executable of the first child process, as
4218
resolved by searching C when the harness is started with L.
4219
Returns undef if the first child is a code reference (not an external
4220
command), or if the harness has not been started yet.
4221
4222
To get the full path of a particular child, do:
4223
4224
$h->full_path( 0 ); # first child's executable path
4225
$h->full_path( 1 ); # second child's executable path
4226
4227
or
4228
4229
($h->full_paths)[0]
4230
($h->full_paths)[1]
4231
4232
=cut
4233
4234
sub full_path {
4235
2
2
1
1469
my IPC::Run $self = shift;
4236
4237
2
100
21
if (@_) {
4238
1
11
my ($which) = @_;
4239
croak(
4240
"Only ",
4241
0
0
scalar( @{ $self->{KIDS} } ),
4242
" child processes, no process $which"
4243
1
50
33
12
) unless $which >= 0 && $which <= $#{ $self->{KIDS} };
1
12
4244
1
15
return $self->{KIDS}->[$which]->{PATH};
4245
}
4246
else {
4247
1
50
6
return undef unless @{ $self->{KIDS} };
1
16
4248
1
16
return $self->{KIDS}->[0]->{PATH};
4249
}
4250
}
4251
4252
=pod
4253
4254
=item full_paths
4255
4256
Returns a list of full paths to the executables of all child processes.
4257
Children that are code references (not external commands) will have C
4258
in the corresponding position.
4259
4260
=cut
4261
4262
sub full_paths {
4263
1
1
1
2
my IPC::Run $self = shift;
4264
4265
1
2
return map { $_->{PATH} } @{ $self->{KIDS} };
1
12
1
8
4266
}
4267
4268
=pod
4269
4270
=item finished
4271
4272
$h->finished;
4273
4274
Returns true if the harness has been started and all child processes have
4275
finished (i.e. C has been called or the harness has run to
4276
completion). Returns false otherwise, including when the harness has not
4277
yet been started.
4278
4279
Unlike L and L, C does not throw an
4280
exception when the harness has not yet run -- it simply returns false.
4281
This makes it safe to call at any point to test completion status.
4282
4283
my $h = harness(\@cmd);
4284
$h->start;
4285
# ... do other work, pump $h as needed ...
4286
if ( $h->finished ) {
4287
print "Exit code: ", $h->result(0), "\n";
4288
}
4289
4290
=cut
4291
4292
sub finished {
4293
20
20
1
152
my IPC::Run $self = $_[0];
4294
20
273
return $self->{STATE} == _finished;
4295
}
4296
4297
##
4298
## Filter Scaffolding
4299
##
4300
use vars (
4301
231
195525
'$filter_op', ## The op running a filter chain right now
4302
'$filter_num', ## Which filter is being run right now.
4303
231
231
1486
);
231
330
4304
4305
##
4306
## A few filters and filter constructors
4307
##
4308
4309
=pod
4310
4311
=back
4312
4313
=back
4314
4315
=head1 FILTERS
4316
4317
These filters are used to modify input our output between a child
4318
process and a scalar or subroutine endpoint.
4319
4320
=over
4321
4322
=item binary
4323
4324
run \@cmd, ">", binary, \$out;
4325
run \@cmd, ">", binary, \$out; ## Any TRUE value to enable
4326
run \@cmd, ">", binary 0, \$out; ## Any FALSE value to disable
4327
4328
This is a constructor for a "binmode" "filter" that tells IPC::Run to keep
4329
the carriage returns that would ordinarily be edited out for you (binmode
4330
is usually off). This is not a real filter, but an option masquerading as
4331
a filter.
4332
4333
It's not named "binmode" because you're likely to want to call Perl's binmode
4334
in programs that are piping binary data around.
4335
4336
=cut
4337
4338
sub binary(;$) {
4339
91
100
91
1
1513025
my $enable = @_ ? shift : 1;
4340
91
91
1128
return bless sub { $enable }, "IPC::Run::binmode_pseudo_filter";
91
338
4341
}
4342
4343
=pod
4344
4345
=item new_chunker
4346
4347
This breaks a stream of data in to chunks, based on an optional
4348
scalar or regular expression parameter. The default is the Perl
4349
input record separator in $/, which is a newline be default.
4350
4351
run \@cmd, '>', new_chunker, \&lines_handler;
4352
run \@cmd, '>', new_chunker( "\r\n" ), \&lines_handler;
4353
4354
Because this uses $/ by default, you should always pass in a parameter
4355
if you are worried about other code (modules, etc) modifying $/.
4356
4357
If this filter is last in a filter chain that dumps in to a scalar,
4358
the scalar must be set to '' before a new chunk will be written to it.
4359
4360
As an example of how a filter like this can be written, here's a
4361
chunker that splits on newlines:
4362
4363
sub line_splitter {
4364
my ( $in_ref, $out_ref ) = @_;
4365
4366
return 0 if length $$out_ref;
4367
4368
return input_avail && do {
4369
while (1) {
4370
if ( $$in_ref =~ s/\A(.*?\n)// ) {
4371
$$out_ref .= $1;
4372
return 1;
4373
}
4374
my $hmm = get_more_input;
4375
unless ( defined $hmm ) {
4376
$$out_ref = $$in_ref;
4377
$$in_ref = '';
4378
return length $$out_ref ? 1 : 0;
4379
}
4380
return 0 if $hmm eq 0;
4381
}
4382
}
4383
};
4384
4385
=cut
4386
4387
sub new_chunker(;$) {
4388
5
5
1
359
my ($re) = @_;
4389
5
100
17
$re = $/ if _empty $re;
4390
5
100
16
$re = quotemeta($re) unless ref $re eq 'Regexp';
4391
5
97
$re = qr/\A(.*?$re)/s;
4392
4393
return sub {
4394
56
56
84
my ( $in_ref, $out_ref ) = @_;
4395
4396
56
50
100
return 0 if length $$out_ref;
4397
4398
56
66
87
return input_avail && do {
4399
while (1) {
4400
if ( $$in_ref =~ s/$re// ) {
4401
$$out_ref .= $1;
4402
return 1;
4403
}
4404
my $hmm = get_more_input;
4405
unless ( defined $hmm ) {
4406
$$out_ref = $$in_ref;
4407
$$in_ref = '';
4408
return length $$out_ref ? 1 : 0;
4409
}
4410
return 0 if $hmm eq 0;
4411
}
4412
}
4413
5
34
};
4414
}
4415
4416
=pod
4417
4418
=item new_appender
4419
4420
This appends a fixed string to each chunk of data read from the source
4421
scalar or sub. This might be useful if you're writing commands to a
4422
child process that always must end in a fixed string, like "\n":
4423
4424
run( \@cmd,
4425
'<', new_appender( "\n" ), \&commands,
4426
);
4427
4428
Here's a typical filter sub that might be created by new_appender():
4429
4430
sub newline_appender {
4431
my ( $in_ref, $out_ref ) = @_;
4432
4433
return input_avail && do {
4434
$$out_ref = join( '', $$out_ref, $$in_ref, "\n" );
4435
$$in_ref = '';
4436
1;
4437
}
4438
};
4439
4440
=cut
4441
4442
sub new_appender($) {
4443
1
1
1
2
my ($suffix) = @_;
4444
1
50
4
croak "\$suffix undefined" unless defined $suffix;
4445
4446
return sub {
4447
10
10
20
my ( $in_ref, $out_ref ) = @_;
4448
4449
10
66
20
return input_avail && do {
4450
$$out_ref = join( '', $$out_ref, $$in_ref, $suffix );
4451
$$in_ref = '';
4452
1;
4453
}
4454
1
6
};
4455
}
4456
4457
=item new_string_source
4458
4459
TODO: Needs confirmation. Was previously undocumented. in this module.
4460
4461
This is a filter which is exportable. Returns a sub which appends the data passed in to the output buffer and returns 1 if data was appended. 0 if it was an empty string and undef if no data was passed.
4462
4463
NOTE: Any additional variables passed to new_string_source will be passed to the sub every time it's called and appended to the output.
4464
4465
=cut
4466
4467
sub new_string_source {
4468
116
116
1
175
my $ref;
4469
116
50
284
if ( @_ > 1 ) {
4470
0
0
$ref = [@_],
4471
}
4472
else {
4473
116
176
$ref = shift;
4474
}
4475
4476
return ref $ref eq 'SCALAR'
4477
? sub {
4478
0
0
0
my ( $in_ref, $out_ref ) = @_;
4479
4480
return defined $$ref
4481
0
0
0
? do {
4482
0
0
$$out_ref .= $$ref;
4483
0
0
0
my $r = length $$ref ? 1 : 0;
4484
0
0
$$ref = undef;
4485
0
0
$r;
4486
}
4487
: undef;
4488
}
4489
: sub {
4490
998
998
1236
my ( $in_ref, $out_ref ) = @_;
4491
4492
return @$ref
4493
998
100
1699
? do {
4494
361
498
my $s = shift @$ref;
4495
361
569
$$out_ref .= $s;
4496
361
100
845
length $s ? 1 : 0;
4497
}
4498
: undef;
4499
}
4500
116
50
930
}
4501
4502
=item new_string_sink
4503
4504
TODO: Needs confirmation. Was previously undocumented.
4505
4506
This is a filter which is exportable. Returns a sub which pops the data out of the input stream and pushes it onto the string.
4507
4508
=cut
4509
4510
sub new_string_sink {
4511
116
116
1
574
my ($string_ref) = @_;
4512
4513
return sub {
4514
1212
1212
1400
my ( $in_ref, $out_ref ) = @_;
4515
4516
1212
66
1695
return input_avail && do {
4517
$$string_ref .= $$in_ref;
4518
$$in_ref = '';
4519
1;
4520
}
4521
116
635
};
4522
}
4523
4524
=pod
4525
4526
=item io
4527
4528
Takes a filename or filehandle, a redirection operator, optional filters,
4529
and a source or destination (depends on the redirection operator). Returns
4530
an IPC::Run::IO object suitable for harness()ing (including via start()
4531
or run()).
4532
4533
This is shorthand for
4534
4535
4536
require IPC::Run::IO;
4537
4538
... IPC::Run::IO->new(...) ...
4539
4540
=cut
4541
4542
sub io {
4543
9
9
1
156161
require IPC::Run::IO;
4544
9
61
IPC::Run::IO->new(@_);
4545
}
4546
4547
=pod
4548
4549
=item timer
4550
4551
$h = start( \@cmd, \$in, \$out, $t = timer( 5 ) );
4552
4553
pump $h until $out =~ /expected stuff/ || $t->is_expired;
4554
4555
Instantiates a non-fatal timer. pump() returns once each time a timer
4556
expires. Has no direct effect on run(), but you can pass a subroutine
4557
to fire when the timer expires.
4558
4559
See L for building timers that throw exceptions on
4560
expiration.
4561
4562
See L for details.
4563
4564
=cut
4565
4566
# Doing the prototype suppresses 'only used once' on older perls.
4567
sub timer;
4568
*timer = \&IPC::Run::Timer::timer;
4569
4570
=pod
4571
4572
=item timeout
4573
4574
$h = start( \@cmd, \$in, \$out, $t = timeout( 5 ) );
4575
4576
pump $h until $out =~ /expected stuff/;
4577
4578
Instantiates a timer that throws an exception when it expires.
4579
If you don't provide an exception, a default exception that matches
4580
/^IPC::Run: .*timed out/ is thrown by default. You can pass in your own
4581
exception scalar or reference:
4582
4583
$h = start(
4584
\@cmd, \$in, \$out,
4585
$t = timeout( 5, exception => 'slowpoke' ),
4586
);
4587
4588
or set the name used in debugging message and in the default exception
4589
string:
4590
4591
$h = start(
4592
\@cmd, \$in, \$out,
4593
timeout( 50, name => 'process timer' ),
4594
$stall_timer = timeout( 5, name => 'stall timer' ),
4595
);
4596
4597
pump $h until $out =~ /started/;
4598
4599
$in = 'command 1';
4600
$stall_timer->start;
4601
pump $h until $out =~ /command 1 finished/;
4602
4603
$in = 'command 2';
4604
$stall_timer->start;
4605
pump $h until $out =~ /command 2 finished/;
4606
4607
$in = 'very slow command 3';
4608
$stall_timer->start( 10 );
4609
pump $h until $out =~ /command 3 finished/;
4610
4611
$stall_timer->start( 5 );
4612
$in = 'command 4';
4613
pump $h until $out =~ /command 4 finished/;
4614
4615
$stall_timer->reset; # Prevent restarting or expirng
4616
finish $h;
4617
4618
See L for building non-fatal timers.
4619
4620
See L for details.
4621
4622
=cut
4623
4624
# Doing the prototype suppresses 'only used once' on older perls.
4625
sub timeout;
4626
*timeout = \&IPC::Run::Timer::timeout;
4627
4628
=pod
4629
4630
=back
4631
4632
=head1 FILTER IMPLEMENTATION FUNCTIONS
4633
4634
These functions are for use from within filters.
4635
4636
=over
4637
4638
=item input_avail
4639
4640
Returns TRUE if input is available. If none is available, then
4641
&get_more_input is called and its result is returned.
4642
4643
This is usually used in preference to &get_more_input so that the
4644
calling filter removes all data from the $in_ref before more data
4645
gets read in to $in_ref.
4646
4647
C is usually used as part of a return expression:
4648
4649
return input_avail && do {
4650
## process the input just gotten
4651
1;
4652
};
4653
4654
This technique allows input_avail to return the undef or 0 that a
4655
filter normally returns when there's no input to process. If a filter
4656
stores intermediate values, however, it will need to react to an
4657
undef:
4658
4659
my $got = input_avail;
4660
if ( ! defined $got ) {
4661
## No more input ever, flush internal buffers to $out_ref
4662
}
4663
return $got unless $got;
4664
## Got some input, move as much as need be
4665
return 1 if $added_to_out_ref;
4666
4667
=cut
4668
4669
sub input_avail() {
4670
confess "Undefined FBUF ref for $filter_num+1"
4671
3109
50
3109
1
9734
unless defined $filter_op->{FBUFS}->[ $filter_num + 1 ];
4672
3109
100
2823
length ${ $filter_op->{FBUFS}->[ $filter_num + 1 ] } || get_more_input;
3109
7210
4673
}
4674
4675
=pod
4676
4677
=item get_more_input
4678
4679
This is used to fetch more input in to the input variable. It returns
4680
undef if there will never be any more input, 0 if there is none now,
4681
but there might be in the future, and TRUE if more input was gotten.
4682
4683
C is usually used as part of a return expression,
4684
see L for more information.
4685
4686
=cut
4687
4688
##
4689
## Filter implementation interface
4690
##
4691
sub get_more_input() {
4692
14255
14255
1
18553
++$filter_num;
4693
14255
18119
my $r = eval {
4694
confess "get_more_input() called and no more filters in chain"
4695
14255
50
34726
unless defined $filter_op->{FILTERS}->[$filter_num];
4696
$filter_op->{FILTERS}->[$filter_num]->(
4697
$filter_op->{FBUFS}->[ $filter_num + 1 ],
4698
14255
54161
$filter_op->{FBUFS}->[$filter_num],
4699
); # if defined ${$filter_op->{FBUFS}->[$filter_num+1]};
4700
};
4701
14255
22972
--$filter_num;
4702
14255
50
23550
die $@ if $@;
4703
14255
30433
return $r;
4704
}
4705
4706
1;
4707
4708
=pod
4709
4710
=back
4711
4712
=head1 TODO
4713
4714
These will be addressed as needed and as time allows.
4715
4716
Stall timeout.
4717
4718
Expose a list of child process objects. When I do this,
4719
each child process is likely to be blessed into IPC::Run::Proc.
4720
4721
$kid->abort(), $kid->kill(), $kid->signal( $num_or_name ).
4722
4723
Write tests for /(full_)?results?/ subs.
4724
4725
Currently, pump() and run() only work on systems where select() works on the
4726
filehandles returned by pipe(). This does *not* include ActiveState on Win32,
4727
although it does work on cygwin under Win32 (thought the tests whine a bit).
4728
I'd like to rectify that, suggestions and patches welcome.
4729
4730
Likewise start() only fully works on fork()/exec() machines (well, just
4731
fork() if you only ever pass perl subs as subprocesses). There's
4732
some scaffolding for calling Open3::spawn_with_handles(), but that's
4733
untested, and not that useful with limited select().
4734
4735
Support for C<\@sub_cmd> as an argument to a command which
4736
gets replaced with /dev/fd or the name of a temporary file containing foo's
4737
output. This is like <(sub_cmd ...) found in bash and csh (IIRC).
4738
4739
Allow multiple harnesses to be combined as independent sets of processes
4740
in to one 'meta-harness'.
4741
4742
Allow a harness to be passed in place of an \@cmd. This would allow
4743
multiple harnesses to be aggregated.
4744
4745
Ability to add external file descriptors w/ filter chains and endpoints.
4746
4747
Ability to add timeouts and timing generators (i.e. repeating timeouts).
4748
4749
High resolution timeouts.
4750
4751
=head1 Win32 LIMITATIONS
4752
4753
=over
4754
4755
=item argument-passing rules are program-specific
4756
4757
Win32 programs receive all arguments in a single "command line" string.
4758
IPC::Run assembles this string so programs using L
4759
rules|https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args#parsing-c-command-line-arguments>
4760
will see an C that matches the array reference specifying the command.
4761
Some programs use different rules to parse their command line. Notable examples
4762
include F, F, and Cygwin programs called from non-Cygwin
4763
programs. Use L to call these and other nonstandard
4764
programs.
4765
4766
=item batch files
4767
4768
Properly escaping a batch file argument depends on how the script will use that
4769
argument, because some uses experience multiple levels of caret (escape
4770
character) removal. Avoid calling batch files with arguments, particularly when
4771
the argument values originate outside your program or contain non-alphanumeric
4772
characters. Perl scripts and PowerShell scripts are sound alternatives. If you
4773
do use batch file arguments, IPC::Run escapes them so the batch file can pass
4774
them, unquoted, to a program having standard command line parsing rules. If the
4775
batch file enables delayed environment variable expansion, it must disable that
4776
feature before expanding its arguments. For example, if F contains
4777
C, C will create a Perl process in which
4778
C<@ARGV> matches C<@list>. Prepending a C line
4779
would make the batch file malfunction, silently. Another silent-malfunction
4780
example is C for F containing C
4781
%*>.
4782
4783
=item Fails on Win9X
4784
4785
If you want Win9X support, you'll have to debug it or fund me because I
4786
don't use that system any more. The Win32 subsysem has been extended to
4787
use temporary files in simple run() invocations and these may actually
4788
work on Win9X too, but I don't have time to work on it.
4789
4790
=item May deadlock on Win2K (but not WinNT4 or WinXPPro)
4791
4792
Spawning more than one subprocess on Win2K causes a deadlock I haven't
4793
figured out yet, but simple uses of run() often work. Passes all tests
4794
on WinXPPro and WinNT.
4795
4796
=item no support yet for pty>
4797
4798
These are likely to be implemented as "<" and ">" with binmode on, not
4799
sure.
4800
4801
=item no support for file descriptors higher than 2 (stderr)
4802
4803
Win32 only allows passing explicit fds 0, 1, and 2. If you really, really need to pass file handles, us Win32API:: GetOsFHandle() or ::FdGetOsFHandle() to
4804
get the integer handle and pass it to the child process using the command
4805
line, environment, stdin, intermediary file, or other IPC mechanism. Then
4806
use that handle in the child (Win32API.pm provides ways to reconstitute
4807
Perl file handles from Win32 file handles).
4808
4809
=item no support for subroutine subprocesses (CODE refs)
4810
4811
Can't fork(), so the subroutines would have no context, and closures certainly
4812
have no meaning
4813
4814
Perhaps with Win32 fork() emulation, this can be supported in a limited
4815
fashion, but there are other very serious problems with that: all parent
4816
fds get dup()ed in to the thread emulating the forked process, and that
4817
keeps the parent from being able to close all of the appropriate fds.
4818
4819
=item no support for init => sub {} routines.
4820
4821
Win32 processes are created from scratch, there is no way to do an init
4822
routine that will affect the running child. Some limited support might
4823
be implemented one day, do chdir() and %ENV changes can be made.
4824
4825
=item signals
4826
4827
Win32 does not fully support signals. signal() is likely to cause errors
4828
unless sending a signal that Perl emulates, and C is immediately
4829
fatal (there is no grace period).
4830
4831
=item C<$?> cannot represent all Win32 exit codes
4832
4833
Prefer C, C, or other IPC::Run methods.
4834
4835
=item helper processes
4836
4837
IPC::Run uses helper processes, one per redirected file, to adapt between the
4838
anonymous pipe connected to the child and the TCP socket connected to the
4839
parent. This is a waste of resources and will change in the future to either
4840
use threads (instead of helper processes) or a WaitForMultipleObjects call
4841
(instead of select). Please contact me if you can help with the
4842
WaitForMultipleObjects() approach; I haven't figured out how to get at it
4843
without C code.
4844
4845
=item shutdown pause
4846
4847
There seems to be a pause of up to 1 second between when a child program exits
4848
and the corresponding sockets indicate that they are closed in the parent.
4849
Not sure why.
4850
4851
=item binmode
4852
4853
binmode is not supported yet. The underpinnings are implemented, just ask
4854
if you need it.
4855
4856
=item IPC::Run::IO
4857
4858
IPC::Run::IO objects can be used on Unix to read or write arbitrary files. On
4859
Win32, they will need to use the same helper processes to adapt from
4860
non-select()able filehandles to select()able ones (or perhaps
4861
WaitForMultipleObjects() will work with them, not sure).
4862
4863
=item startup race conditions
4864
4865
There seems to be an occasional race condition between child process startup
4866
and pipe closings. It seems like if the child is not fully created by the time
4867
CreateProcess returns and we close the TCP socket being handed to it, the
4868
parent socket can also get closed. This is seen with the Win32 pumper
4869
applications, not the "real" child process being spawned.
4870
4871
I assume this is because the kernel hasn't gotten around to incrementing the
4872
reference count on the child's end (since the child was slow in starting), so
4873
the parent's closing of the child end causes the socket to be closed, thus
4874
closing the parent socket.
4875
4876
Being a race condition, it's hard to reproduce, but I encountered it while
4877
testing this code on a drive share to a samba box. In this case, it takes
4878
t/run.t a long time to spawn its child processes (the parent hangs in the
4879
first select for several seconds until the child emits any debugging output).
4880
4881
I have not seen it on local drives, and can't reproduce it at will,
4882
unfortunately. The symptom is a "bad file descriptor in select()" error, and,
4883
by turning on debugging, it's possible to see that select() is being called on
4884
a no longer open file descriptor that was returned from the _socket() routine
4885
in Win32Helper. There's a new confess() that checks for this ("PARENT_HANDLE
4886
no longer open"), but I haven't been able to reproduce it (typically).
4887
4888
=back
4889
4890
=head1 LIMITATIONS
4891
4892
On Unix, requires a system that supports C so
4893
it can tell if a child process is still running.
4894
4895
PTYs don't seem to be non-blocking on some versions of Solaris. Here's a
4896
test script contributed by Borislav Deianov to see
4897
if you have the problem. If it dies, you have the problem.
4898
4899
#!/usr/bin/perl
4900
4901
use IPC::Run qw(run);
4902
use Fcntl;
4903
use IO::Pty;
4904
4905
sub makecmd {
4906
return ['perl', '-e',
4907
', print "\n" x '.$_[0].'; while(){last if /end/}'];
4908
}
4909
4910
#pipe R, W;
4911
#fcntl(W, F_SETFL, O_NONBLOCK);
4912
#while (syswrite(W, "\n", 1)) { $pipebuf++ };
4913
#print "pipe buffer size is $pipebuf\n";
4914
my $pipebuf=4096;
4915
my $in = "\n" x ($pipebuf * 2) . "end\n";
4916
my $out;
4917
4918
$SIG{ALRM} = sub { die "Never completed!\n" };
4919
4920
print "reading from scalar via pipe...";
4921
alarm( 2 );
4922
run(makecmd($pipebuf * 2), '<', \$in, '>', \$out);
4923
alarm( 0 );
4924
print "done\n";
4925
4926
print "reading from code via pipe... ";
4927
alarm( 2 );
4928
run(makecmd($pipebuf * 3), '<', sub { $t = $in; undef $in; $t}, '>', \$out);
4929
alarm( 0 );
4930
print "done\n";
4931
4932
$pty = IO::Pty->new();
4933
$pty->blocking(0);
4934
$slave = $pty->slave();
4935
while ($pty->syswrite("\n", 1)) { $ptybuf++ };
4936
print "pty buffer size is $ptybuf\n";
4937
$in = "\n" x ($ptybuf * 3) . "end\n";
4938
4939
print "reading via pty... ";
4940
alarm( 2 );
4941
run(makecmd($ptybuf * 3), '', \$out);
4942
alarm(0);
4943
print "done\n";
4944
4945
IO::Pty version 1.21 and later added a C method that automatically
4946
closes the cached slave pty handle when the master is destroyed. IPC::Run
4947
works around this by detaching the slave before closing the master in the
4948
child process; no user action is required.
4949
4950
No support for ';', '&&', '||', '{ ... }', etc: use perl's, since run()
4951
returns TRUE when the command exits with a 0 result code.
4952
4953
Does not provide shell-like string interpolation.
4954
4955
No support for C or C: do C in an init() sub.
4956
4957
For setting environment variables in the child process without affecting the
4958
parent, use the C option (a hash reference of key/value pairs):
4959
4960
run(
4961
\cmd,
4962
...
4963
env => { FOO => 'BAR', BAZ => 'QUX' }
4964
);
4965
4966
The C variables are applied in the child process before any C subs
4967
run, so C can still override individual variables if needed. The parent
4968
process C<%ENV> is not modified.
4969
4970
Alternatively, use an C sub for more complex setup:
4971
4972
run(
4973
\cmd,
4974
...
4975
init => sub {
4976
chdir $dir or die $!;
4977
$ENV{FOO}='BAR'
4978
}
4979
);
4980
4981
Timeout calculation does not allow absolute times, or specification of
4982
days, months, etc.
4983
4984
B Function coprocesses (C) suffer from two
4985
limitations. The first is that it is difficult to close all filehandles the
4986
child inherits from the parent, since there is no way to scan all open
4987
FILEHANDLEs in Perl and it is both painful and a bit dangerous to close all open
4988
file descriptors with C. Painful because we can't tell which
4989
fds are open at the POSIX level, either, so we'd have to scan all possible fds
4990
and close any that we don't want open (normally C closes any
4991
non-inheritable but we don't C for &sub processes).
4992
4993
The second problem is that Perl's DESTROY subs and other on-exit cleanup gets
4994
run in the child process. If objects are instantiated in the parent before the
4995
child is forked, the DESTROY will get run once in the parent and once in
4996
the child. When coprocess subs exit, POSIX::_exit is called to work around this,
4997
but it means that objects that are still referred to at that time are not
4998
cleaned up. So setting package vars or closure vars to point to objects that
4999
rely on DESTROY to affect things outside the process (files, etc), will
5000
lead to bugs.
5001
5002
I goofed on the syntax: "filename" are both
5003
oddities.
5004
5005
=head1 TODO
5006
5007
=over
5008
5009
=item Allow one harness to "adopt" another:
5010
5011
$new_h = harness \@cmd2;
5012
$h->adopt( $new_h );
5013
5014
=item Close all filehandles not explicitly marked to stay open.
5015
5016
The problem with this one is that there's no good way to scan all open
5017
FILEHANDLEs in Perl, yet you don't want child processes inheriting handles
5018
willy-nilly.
5019
5020
=back
5021
5022
=head1 INSPIRATION
5023
5024
Well, select() and waitpid() badly needed wrapping, and open3() isn't
5025
open-minded enough for me.
5026
5027
The shell-like API inspired by a message Russ Allbery sent to perl5-porters,
5028
which included:
5029
5030
I've thought for some time that it would be
5031
nice to have a module that could handle full Bourne shell pipe syntax
5032
internally, with fork and exec, without ever invoking a shell. Something
5033
that you could give things like:
5034
5035
pipeopen (PIPE, [ qw/cat file/ ], '|', [ 'analyze', @args ], '>&3');
5036
5037
Message ylln51p2b6.fsf@windlord.stanford.edu, on 2000/02/04.
5038
5039
=head1 SUPPORT
5040
5041
Bugs should always be submitted via the GitHub bug tracker
5042
5043
L
5044
5045
=head1 AUTHORS
5046
5047
Adam Kennedy
5048
5049
Barrie Slaymaker
5050
5051
=head1 COPYRIGHT
5052
5053
Some parts copyright 2008 - 2009 Adam Kennedy.
5054
5055
Copyright 1999 Barrie Slaymaker.
5056
5057
You may distribute under the terms of either the GNU General Public
5058
License or the Artistic License, as specified in the README file.
5059
5060
=cut