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