Add built local::lib
[catagits/Gitalist.git] / local-lib5 / man / man3 / IPC::Run.3pm
CommitLineData
3fea05b9 1.\" Automatically generated by Pod::Man 2.22 (Pod::Simple 3.10)
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sp \" Vertical space (when we can't use .PP)
6.if t .sp .5v
7.if n .sp
8..
9.de Vb \" Begin verbatim text
10.ft CW
11.nf
12.ne \\$1
13..
14.de Ve \" End verbatim text
15.ft R
16.fi
17..
18.\" Set up some character translations and predefined strings. \*(-- will
19.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
20.\" double quote, and \*(R" will give a right double quote. \*(C+ will
21.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
22.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
23.\" nothing in troff, for use with C<>.
24.tr \(*W-
25.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
26.ie n \{\
27. ds -- \(*W-
28. ds PI pi
29. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
30. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
31. ds L" ""
32. ds R" ""
33. ds C` ""
34. ds C' ""
35'br\}
36.el\{\
37. ds -- \|\(em\|
38. ds PI \(*p
39. ds L" ``
40. ds R" ''
41'br\}
42.\"
43.\" Escape single quotes in literal strings from groff's Unicode transform.
44.ie \n(.g .ds Aq \(aq
45.el .ds Aq '
46.\"
47.\" If the F register is turned on, we'll generate index entries on stderr for
48.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
49.\" entries marked with X<> in POD. Of course, you'll have to process the
50.\" output yourself in some meaningful fashion.
51.ie \nF \{\
52. de IX
53. tm Index:\\$1\t\\n%\t"\\$2"
54..
55. nr % 0
56. rr F
57.\}
58.el \{\
59. de IX
60..
61.\}
62.\"
63.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
64.\" Fear. Run. Save yourself. No user-serviceable parts.
65. \" fudge factors for nroff and troff
66.if n \{\
67. ds #H 0
68. ds #V .8m
69. ds #F .3m
70. ds #[ \f1
71. ds #] \fP
72.\}
73.if t \{\
74. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
75. ds #V .6m
76. ds #F 0
77. ds #[ \&
78. ds #] \&
79.\}
80. \" simple accents for nroff and troff
81.if n \{\
82. ds ' \&
83. ds ` \&
84. ds ^ \&
85. ds , \&
86. ds ~ ~
87. ds /
88.\}
89.if t \{\
90. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
91. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
92. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
93. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
94. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
95. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
96.\}
97. \" troff and (daisy-wheel) nroff accents
98.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
99.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
100.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
101.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
102.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
103.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
104.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
105.ds ae a\h'-(\w'a'u*4/10)'e
106.ds Ae A\h'-(\w'A'u*4/10)'E
107. \" corrections for vroff
108.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
109.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
110. \" for low resolution devices (crt and lpr)
111.if \n(.H>23 .if \n(.V>19 \
112\{\
113. ds : e
114. ds 8 ss
115. ds o a
116. ds d- d\h'-1'\(ga
117. ds D- D\h'-1'\(hy
118. ds th \o'bp'
119. ds Th \o'LP'
120. ds ae ae
121. ds Ae AE
122.\}
123.rm #[ #] #H #V #F C
124.\" ========================================================================
125.\"
126.IX Title "IPC::Run 3"
127.TH IPC::Run 3 "2009-07-13" "perl v5.8.7" "User Contributed Perl Documentation"
128.\" For nroff, turn off justification. Always turn off hyphenation; it makes
129.\" way too many mistakes in technical documents.
130.if n .ad l
131.nh
132.SH "NAME"
133IPC::Run \- system() and background procs w/ piping, redirs, ptys (Unix, Win32)
134.SH "SYNOPSIS"
135.IX Header "SYNOPSIS"
136.Vb 2
137\& ## First,a command to run:
138\& my @cat = qw( cat );
139\&
140\& ## Using run() instead of system():
141\& use IPC::Run qw( run timeout );
142\&
143\& run \e@cmd, \e$in, \e$out, \e$err, timeout( 10 ) or die "cat: $?"
144\&
145\& # Can do I/O to sub refs and filenames, too:
146\& run \e@cmd, \*(Aq<\*(Aq, "in.txt", \e&out, \e&err or die "cat: $?"
147\& run \e@cat, \*(Aq<\*(Aq, "in.txt", \*(Aq>>\*(Aq, "out.txt", \*(Aq2>>\*(Aq, "err.txt";
148\&
149\&
150\& # Redirecting using psuedo\-terminals instad of pipes.
151\& run \e@cat, \*(Aq<pty<\*(Aq, \e$in, \*(Aq>pty>\*(Aq, \e$out_and_err;
152\&
153\& ## Scripting subprocesses (like Expect):
154\&
155\& use IPC::Run qw( start pump finish timeout );
156\&
157\& # Incrementally read from / write to scalars.
158\& # $in is drained as it is fed to cat\*(Aqs stdin,
159\& # $out accumulates cat\*(Aqs stdout
160\& # $err accumulates cat\*(Aqs stderr
161\& # $h is for "harness".
162\& my $h = start \e@cat, \e$in, \e$out, \e$err, timeout( 10 );
163\&
164\& $in .= "some input\en";
165\& pump $h until $out =~ /input\en/g;
166\&
167\& $in .= "some more input\en";
168\& pump $h until $out =~ /\eG.*more input\en/;
169\&
170\& $in .= "some final input\en";
171\& finish $h or die "cat returned $?";
172\&
173\& warn $err if $err;
174\& print $out; ## All of cat\*(Aqs output
175\&
176\& # Piping between children
177\& run \e@cat, \*(Aq|\*(Aq, \e@gzip;
178\&
179\& # Multiple children simultaneously (run() blocks until all
180\& # children exit, use start() for background execution):
181\& run \e@foo1, \*(Aq&\*(Aq, \e@foo2;
182\&
183\& # Calling \e&set_up_child in the child before it executes the
184\& # command (only works on systems with true fork() & exec())
185\& # exceptions thrown in set_up_child() will be propagated back
186\& # to the parent and thrown from run().
187\& run \e@cat, \e$in, \e$out,
188\& init => \e&set_up_child;
189\&
190\& # Read from / write to file handles you open and close
191\& open IN, \*(Aq<in.txt\*(Aq or die $!;
192\& open OUT, \*(Aq>out.txt\*(Aq or die $!;
193\& print OUT "preamble\en";
194\& run \e@cat, \e*IN, \e*OUT or die "cat returned $?";
195\& print OUT "postamble\en";
196\& close IN;
197\& close OUT;
198\&
199\& # Create pipes for you to read / write (like IPC::Open2 & 3).
200\& $h = start
201\& \e@cat,
202\& \*(Aq<pipe\*(Aq, \e*IN,
203\& \*(Aq>pipe\*(Aq, \e*OUT,
204\& \*(Aq2>pipe\*(Aq, \e*ERR
205\& or die "cat returned $?";
206\& print IN "some input\en";
207\& close IN;
208\& print <OUT>, <ERR>;
209\& finish $h;
210\&
211\& # Mixing input and output modes
212\& run \e@cat, \*(Aqin.txt\*(Aq, \e&catch_some_out, \e*ERR_LOG );
213\&
214\& # Other redirection constructs
215\& run \e@cat, \*(Aq>&\*(Aq, \e$out_and_err;
216\& run \e@cat, \*(Aq2>&1\*(Aq;
217\& run \e@cat, \*(Aq0<&3\*(Aq;
218\& run \e@cat, \*(Aq<&\-\*(Aq;
219\& run \e@cat, \*(Aq3<\*(Aq, \e$in3;
220\& run \e@cat, \*(Aq4>\*(Aq, \e$out4;
221\& # etc.
222\&
223\& # Passing options:
224\& run \e@cat, \*(Aqin.txt\*(Aq, debug => 1;
225\&
226\& # Call this system\*(Aqs shell, returns TRUE on 0 exit code
227\& # THIS IS THE OPPOSITE SENSE OF system()\*(Aqs RETURN VALUE
228\& run "cat a b c" or die "cat returned $?";
229\&
230\& # Launch a sub process directly, no shell. Can\*(Aqt do redirection
231\& # with this form, it\*(Aqs here to behave like system() with an
232\& # inverted result.
233\& $r = run "cat a b c";
234\&
235\& # Read from a file in to a scalar
236\& run io( "filename", \*(Aqr\*(Aq, \e$recv );
237\& run io( \e*HANDLE, \*(Aqr\*(Aq, \e$recv );
238.Ve
239.SH "DESCRIPTION"
240.IX Header "DESCRIPTION"
241IPC::Run allows you run and interact with child processes using files, pipes,
242and pseudo-ttys. Both \fIsystem()\fR\-style and scripted usages are supported and
243may be mixed. Likewise, functional and \s-1OO\s0 \s-1API\s0 styles are both supported and
244may be mixed.
245.PP
246Various redirection operators reminiscent of those seen on common Unix and \s-1DOS\s0
247command lines are provided.
248.PP
249Before digging in to the details a few \s-1LIMITATIONS\s0 are important enough
250to be mentioned right up front:
251.IP "Win32 Support" 4
252.IX Item "Win32 Support"
253Win32 support is working but \fB\s-1EXPERIMENTAL\s0\fR, but does pass all relevant tests
254on \s-1NT\s0 4.0. See \*(L"Win32 \s-1LIMITATIONS\s0\*(R".
255.IP "pty Support" 4
256.IX Item "pty Support"
257If you need pty support, IPC::Run should work well enough most of the
258time, but IO::Pty is being improved, and IPC::Run will be improved to
259use IO::Pty's new features when it is release.
260.Sp
261The basic problem is that the pty needs to initialize itself before the
262parent writes to the master pty, or the data written gets lost. So
263IPC::Run does a \fIsleep\fR\|(1) in the parent after forking to (hopefully) give
264the child a chance to run. This is a kludge that works well on non
265heavily loaded systems :(.
266.Sp
267ptys are not supported yet under Win32, but will be emulated...
268.IP "Debugging Tip" 4
269.IX Item "Debugging Tip"
270You may use the environment variable \f(CW\*(C`IPCRUNDEBUG\*(C'\fR to see what's going on
271under the hood:
272.Sp
273.Vb 5
274\& $ IPCRUNDEBUG=basic myscript # prints minimal debugging
275\& $ IPCRUNDEBUG=data myscript # prints all data reads/writes
276\& $ IPCRUNDEBUG=details myscript # prints lots of low\-level details
277\& $ IPCRUNDEBUG=gory myscript # (Win32 only) prints data moving through
278\& # the helper processes.
279.Ve
280.PP
281We now return you to your regularly scheduled documentation.
282.SS "Harnesses"
283.IX Subsection "Harnesses"
284Child processes and I/O handles are gathered in to a harness, then
285started and run until the processing is finished or aborted.
286.SS "\fIrun()\fP vs. \fIstart()\fP; \fIpump()\fP; \fIfinish()\fP;"
287.IX Subsection "run() vs. start(); pump(); finish();"
288There are two modes you can run harnesses in: \fIrun()\fR functions as an
289enhanced \fIsystem()\fR, and \fIstart()\fR/\fIpump()\fR/\fIfinish()\fR allow for background
290processes and scripted interactions with them.
291.PP
292When using \fIrun()\fR, all data to be sent to the harness is set up in
293advance (though one can feed subprocesses input from subroutine refs to
294get around this limitation). The harness is run and all output is
295collected from it, then any child processes are waited for:
296.PP
297.Vb 3
298\& run \e@cmd, \e<<IN, \e$out;
299\& blah
300\& IN
301\&
302\& ## To precompile harnesses and run them later:
303\& my $h = harness \e@cmd, \e<<IN, \e$out;
304\& blah
305\& IN
306\&
307\& run $h;
308.Ve
309.PP
310The background and scripting \s-1API\s0 is provided by \fIstart()\fR, \fIpump()\fR, and
311\&\fIfinish()\fR: \fIstart()\fR creates a harness if need be (by calling \fIharness()\fR)
312and launches any subprocesses, \fIpump()\fR allows you to poll them for
313activity, and \fIfinish()\fR then monitors the harnessed activities until they
314complete.
315.PP
316.Vb 3
317\& ## Build the harness, open all pipes, and launch the subprocesses
318\& my $h = start \e@cat, \e$in, \e$out;
319\& $in = "first input\en";
320\&
321\& ## Now do I/O. start() does no I/O.
322\& pump $h while length $in; ## Wait for all input to go
323\&
324\& ## Now do some more I/O.
325\& $in = "second input\en";
326\& pump $h until $out =~ /second input/;
327\&
328\& ## Clean up
329\& finish $h or die "cat returned $?";
330.Ve
331.PP
332You can optionally compile the harness with \fIharness()\fR prior to
333\&\fIstart()\fRing or \fIrun()\fRing, and you may omit \fIstart()\fR between \fIharness()\fR and
334\&\fIpump()\fR. You might want to do these things if you compile your harnesses
335ahead of time.
336.SS "Using regexps to match output"
337.IX Subsection "Using regexps to match output"
338As shown in most of the scripting examples, the read-to-scalar facility
339for gathering subcommand's output is often used with regular expressions
340to detect stopping points. This is because subcommand output often
341arrives in dribbles and drabs, often only a character or line at a time.
342This output is input for the main program and piles up in variables like
343the \f(CW$out\fR and \f(CW$err\fR in our examples.
344.PP
345Regular expressions can be used to wait for appropriate output in
346several ways. The \f(CW\*(C`cat\*(C'\fR example in the previous section demonstrates
347how to \fIpump()\fR until some string appears in the output. Here's an
348example that uses \f(CW\*(C`smb\*(C'\fR to fetch files from a remote server:
349.PP
350.Vb 1
351\& $h = harness \e@smbclient, \e$in, \e$out;
352\&
353\& $in = "cd /src\en";
354\& $h\->pump until $out =~ /^smb.*> \eZ/m;
355\& die "error cding to /src:\en$out" if $out =~ "ERR";
356\& $out = \*(Aq\*(Aq;
357\&
358\& $in = "mget *\en";
359\& $h\->pump until $out =~ /^smb.*> \eZ/m;
360\& die "error retrieving files:\en$out" if $out =~ "ERR";
361\&
362\& $in = "quit\en";
363\& $h\->finish;
364.Ve
365.PP
366Notice that we carefully clear \f(CW$out\fR after the first command/response
367cycle? That's because IPC::Run does not delete \f(CW$out\fR when we continue,
368and we don't want to trip over the old output in the second
369command/response cycle.
370.PP
371Say you want to accumulate all the output in \f(CW$out\fR and analyze it
372afterwards. Perl offers incremental regular expression matching using
373the \f(CW\*(C`m//gc\*(C'\fR and pattern matching idiom and the \f(CW\*(C`\eG\*(C'\fR assertion.
374IPC::Run is careful not to disturb the current \f(CW\*(C`pos()\*(C'\fR value for
375scalars it appends data to, so we could modify the above so as not to
376destroy \f(CW$out\fR by adding a couple of \f(CW\*(C`/gc\*(C'\fR modifiers. The \f(CW\*(C`/g\*(C'\fR keeps us
377from tripping over the previous prompt and the \f(CW\*(C`/c\*(C'\fR keeps us from
378resetting the prior match position if the expected prompt doesn't
379materialize immediately:
380.PP
381.Vb 1
382\& $h = harness \e@smbclient, \e$in, \e$out;
383\&
384\& $in = "cd /src\en";
385\& $h\->pump until $out =~ /^smb.*> \eZ/mgc;
386\& die "error cding to /src:\en$out" if $out =~ "ERR";
387\&
388\& $in = "mget *\en";
389\& $h\->pump until $out =~ /^smb.*> \eZ/mgc;
390\& die "error retrieving files:\en$out" if $out =~ "ERR";
391\&
392\& $in = "quit\en";
393\& $h\->finish;
394\&
395\& analyze( $out );
396.Ve
397.PP
398When using this technique, you may want to preallocate \f(CW$out\fR to have
399plenty of memory or you may find that the act of growing \f(CW$out\fR each time
400new input arrives causes an \f(CW\*(C`O(length($out)^2)\*(C'\fR slowdown as \f(CW$out\fR grows.
401Say we expect no more than 10,000 characters of input at the most. To
402preallocate memory to \f(CW$out\fR, do something like:
403.PP
404.Vb 2
405\& my $out = "x" x 10_000;
406\& $out = "";
407.Ve
408.PP
409\&\f(CW\*(C`perl\*(C'\fR will allocate at least 10,000 characters' worth of space, then
410mark the \f(CW$out\fR as having 0 length without freeing all that yummy \s-1RAM\s0.
411.SS "Timeouts and Timers"
412.IX Subsection "Timeouts and Timers"
413More than likely, you don't want your subprocesses to run forever, and
414sometimes it's nice to know that they're going a little slowly.
415Timeouts throw exceptions after a some time has elapsed, timers merely
416cause \fIpump()\fR to return after some time has elapsed. Neither is
417reset/restarted automatically.
418.PP
419Timeout objects are created by calling timeout( \f(CW$interval\fR ) and passing
420the result to \fIrun()\fR, \fIstart()\fR or \fIharness()\fR. The timeout period starts
421ticking just after all the child processes have been \fIfork()\fRed or
422\&\fIspawn()\fRed, and are polled for expiration in \fIrun()\fR, \fIpump()\fR and \fIfinish()\fR.
423If/when they expire, an exception is thrown. This is typically useful
424to keep a subprocess from taking too long.
425.PP
426If a timeout occurs in \fIrun()\fR, all child processes will be terminated and
427all file/pipe/ptty descriptors opened by \fIrun()\fR will be closed. File
428descriptors opened by the parent process and passed in to \fIrun()\fR are not
429closed in this event.
430.PP
431If a timeout occurs in \fIpump()\fR, \fIpump_nb()\fR, or \fIfinish()\fR, it's up to you to
432decide whether to \fIkill_kill()\fR all the children or to implement some more
433graceful fallback. No I/O will be closed in \fIpump()\fR, \fIpump_nb()\fR or
434\&\fIfinish()\fR by such an exception (though I/O is often closed down in those
435routines during the natural course of events).
436.PP
437Often an exception is too harsh. timer( \f(CW$interval\fR ) creates timer
438objects that merely prevent \fIpump()\fR from blocking forever. This can be
439useful for detecting stalled I/O or printing a soothing message or \*(L".\*(R"
440to pacify an anxious user.
441.PP
442Timeouts and timers can both be restarted at any time using the timer's
443\&\fIstart()\fR method (this is not the \fIstart()\fR that launches subprocesses). To
444restart a timer, you need to keep a reference to the timer:
445.PP
446.Vb 2
447\& ## Start with a nice long timeout to let smbclient connect. If
448\& ## pump or finish take too long, an exception will be thrown.
449\&
450\& my $h;
451\& eval {
452\& $h = harness \e@smbclient, \e$in, \e$out, \e$err, ( my $t = timeout 30 );
453\& sleep 11; # No effect: timer not running yet
454\&
455\& start $h;
456\& $in = "cd /src\en";
457\& pump $h until ! length $in;
458\&
459\& $in = "ls\en";
460\& ## Now use a short timeout, since this should be faster
461\& $t\->start( 5 );
462\& pump $h until ! length $in;
463\&
464\& $t\->start( 10 ); ## Give smbclient a little while to shut down.
465\& $h\->finish;
466\& };
467\& if ( $@ ) {
468\& my $x = $@; ## Preserve $@ in case another exception occurs
469\& $h\->kill_kill; ## kill it gently, then brutally if need be, or just
470\& ## brutally on Win32.
471\& die $x;
472\& }
473.Ve
474.PP
475Timeouts and timers are \fInot\fR checked once the subprocesses are shut
476down; they will not expire in the interval between the last valid
477process and when IPC::Run scoops up the processes' result codes, for
478instance.
479.SS "Spawning synchronization, child exception propagation"
480.IX Subsection "Spawning synchronization, child exception propagation"
481\&\fIstart()\fR pauses the parent until the child executes the command or \s-1CODE\s0
482reference and propagates any exceptions thrown (including \fIexec()\fR
483failure) back to the parent. This has several pleasant effects: any
484exceptions thrown in the child, including \fIexec()\fR failure, come flying
485out of \fIstart()\fR or \fIrun()\fR as though they had ocurred in the parent.
486.PP
487This includes exceptions your code thrown from init subs. In this
488example:
489.PP
490.Vb 4
491\& eval {
492\& run \e@cmd, init => sub { die "blast it! foiled again!" };
493\& };
494\& print $@;
495.Ve
496.PP
497the exception \*(L"blast it! foiled again\*(R" will be thrown from the child
498process (preventing the \fIexec()\fR) and printed by the parent.
499.PP
500In situations like
501.PP
502.Vb 1
503\& run \e@cmd1, "|", \e@cmd2, "|", \e@cmd3;
504.Ve
505.PP
506\&\f(CW@cmd1\fR will be initted and \fIexec()\fRed before \f(CW@cmd2\fR, and \f(CW@cmd2\fR before \f(CW@cmd3\fR.
507This can save time and prevent oddball errors emitted by later commands
508when earlier commands fail to execute. Note that IPC::Run doesn't start
509any commands unless it can find the executables referenced by all
510commands. These executables must pass both the \f(CW\*(C`\-f\*(C'\fR and \f(CW\*(C`\-x\*(C'\fR tests
511described in perlfunc.
512.PP
513Another nice effect is that \fIinit()\fR subs can take their time doing things
514and there will be no problems caused by a parent continuing to execute
515before a child's \fIinit()\fR routine is complete. Say the \fIinit()\fR routine
516needs to open a socket or a temp file that the parent wants to connect
517to; without this synchronization, the parent will need to implement a
518retry loop to wait for the child to run, since often, the parent gets a
519lot of things done before the child's first timeslice is allocated.
520.PP
521This is also quite necessary for pseudo-tty initialization, which needs
522to take place before the parent writes to the child via pty. Writes
523that occur before the pty is set up can get lost.
524.PP
525A final, minor, nicety is that debugging output from the child will be
526emitted before the parent continues on, making for much clearer debugging
527output in complex situations.
528.PP
529The only drawback I can conceive of is that the parent can't continue to
530operate while the child is being initted. If this ever becomes a
531problem in the field, we can implement an option to avoid this behavior,
532but I don't expect it to.
533.PP
534\&\fBWin32\fR: executing \s-1CODE\s0 references isn't supported on Win32, see
535\&\*(L"Win32 \s-1LIMITATIONS\s0\*(R" for details.
536.SS "Syntax"
537.IX Subsection "Syntax"
538\&\fIrun()\fR, \fIstart()\fR, and \fIharness()\fR can all take a harness specification
539as input. A harness specification is either a single string to be passed
540to the systems' shell:
541.PP
542.Vb 1
543\& run "echo \*(Aqhi there\*(Aq";
544.Ve
545.PP
546or a list of commands, io operations, and/or timers/timeouts to execute.
547Consecutive commands must be separated by a pipe operator '|' or an '&'.
548External commands are passed in as array references, and, on systems
549supporting \fIfork()\fR, Perl code may be passed in as subs:
550.PP
551.Vb 6
552\& run \e@cmd;
553\& run \e@cmd1, \*(Aq|\*(Aq, \e@cmd2;
554\& run \e@cmd1, \*(Aq&\*(Aq, \e@cmd2;
555\& run \e&sub1;
556\& run \e&sub1, \*(Aq|\*(Aq, \e&sub2;
557\& run \e&sub1, \*(Aq&\*(Aq, \e&sub2;
558.Ve
559.PP
560\&'|' pipes the stdout of \e@cmd1 the stdin of \e@cmd2, just like a
561shell pipe. '&' does not. Child processes to the right of a '&'
562will have their stdin closed unless it's redirected-to.
563.PP
564IPC::Run::IO objects may be passed in as well, whether or not
565child processes are also specified:
566.PP
567.Vb 1
568\& run io( "infile", ">", \e$in ), io( "outfile", "<", \e$in );
569.Ve
570.PP
571as can IPC::Run::Timer objects:
572.PP
573.Vb 1
574\& run \e@cmd, io( "outfile", "<", \e$in ), timeout( 10 );
575.Ve
576.PP
577Commands may be followed by scalar, sub, or i/o handle references for
578redirecting
579child process input & output:
580.PP
581.Vb 4
582\& run \e@cmd, \eundef, \e$out;
583\& run \e@cmd, \e$in, \e$out;
584\& run \e@cmd1, \e&in, \*(Aq|\*(Aq, \e@cmd2, \e*OUT;
585\& run \e@cmd1, \e*IN, \*(Aq|\*(Aq, \e@cmd2, \e&out;
586.Ve
587.PP
588This is known as succinct redirection syntax, since \fIrun()\fR, \fIstart()\fR
589and \fIharness()\fR, figure out which file descriptor to redirect and how.
590File descriptor 0 is presumed to be an input for
591the child process, all others are outputs. The assumed file
592descriptor always starts at 0, unless the command is being piped to,
593in which case it starts at 1.
594.PP
595To be explicit about your redirects, or if you need to do more complex
596things, there's also a redirection operator syntax:
597.PP
598.Vb 8
599\& run \e@cmd, \*(Aq<\*(Aq, \eundef, \*(Aq>\*(Aq, \e$out;
600\& run \e@cmd, \*(Aq<\*(Aq, \eundef, \*(Aq>&\*(Aq, \e$out_and_err;
601\& run(
602\& \e@cmd1,
603\& \*(Aq<\*(Aq, \e$in,
604\& \*(Aq|\*(Aq, \e@cmd2,
605\& \e$out
606\& );
607.Ve
608.PP
609Operator syntax is required if you need to do something other than simple
610redirection to/from scalars or subs, like duping or closing file descriptors
611or redirecting to/from a named file. The operators are covered in detail
612below.
613.PP
614After each \e@cmd (or \e&foo), parsing begins in succinct mode and toggles to
615operator syntax mode when an operator (ie plain scalar, not a ref) is seen.
616Once in
617operator syntax mode, parsing only reverts to succinct mode when a '|' or
618\&'&' is seen.
619.PP
620In succinct mode, each parameter after the \e@cmd specifies what to
621do with the next highest file descriptor. These File descriptor start
622with 0 (stdin) unless stdin is being piped to (\f(CW\*(C`\*(Aq|\*(Aq, \e@cmd\*(C'\fR), in which
623case they start with 1 (stdout). Currently, being on the left of
624a pipe (\f(CW\*(C`\e@cmd, \e$out, \e$err, \*(Aq|\*(Aq\*(C'\fR) does \fInot\fR cause stdout to be
625skipped, though this may change since it's not as DWIMerly as it
626could be. Only stdin is assumed to be an
627input in succinct mode, all others are assumed to be outputs.
628.PP
629If no piping or redirection is specified for a child, it will inherit
630the parent's open file handles as dictated by your system's
631close-on-exec behavior and the $^F flag, except that processes after a
632\&'&' will not inherit the parent's stdin. Also note that $^F does not
633affect file desciptors obtained via \s-1POSIX\s0, since it only applies to
634full-fledged Perl file handles. Such processes will have their stdin
635closed unless it has been redirected-to.
636.PP
637If you want to close a child processes stdin, you may do any of:
638.PP
639.Vb 4
640\& run \e@cmd, \eundef;
641\& run \e@cmd, \e"";
642\& run \e@cmd, \*(Aq<&\-\*(Aq;
643\& run \e@cmd, \*(Aq0<&\-\*(Aq;
644.Ve
645.PP
646Redirection is done by placing redirection specifications immediately
647after a command or child subroutine:
648.PP
649.Vb 2
650\& run \e@cmd1, \e$in, \*(Aq|\*(Aq, \e@cmd2, \e$out;
651\& run \e@cmd1, \*(Aq<\*(Aq, \e$in, \*(Aq|\*(Aq, \e@cmd2, \*(Aq>\*(Aq, \e$out;
652.Ve
653.PP
654If you omit the redirection operators, descriptors are counted
655starting at 0. Descriptor 0 is assumed to be input, all others
656are outputs. A leading '|' consumes descriptor 0, so this
657works as expected.
658.PP
659.Vb 1
660\& run \e@cmd1, \e$in, \*(Aq|\*(Aq, \e@cmd2, \e$out;
661.Ve
662.PP
663The parameter following a redirection operator can be a scalar ref,
664a subroutine ref, a file name, an open filehandle, or a closed
665filehandle.
666.PP
667If it's a scalar ref, the child reads input from or sends output to
668that variable:
669.PP
670.Vb 3
671\& $in = "Hello World.\en";
672\& run \e@cat, \e$in, \e$out;
673\& print $out;
674.Ve
675.PP
676Scalars used in incremental (\fIstart()\fR/\fIpump()\fR/\fIfinish()\fR) applications are treated
677as queues: input is removed from input scalers, resulting in them dwindling
678to '', and output is appended to output scalars. This is not true of
679harnesses \fIrun()\fR in batch mode.
680.PP
681It's usually wise to append new input to be sent to the child to the input
682queue, and you'll often want to zap output queues to '' before pumping.
683.PP
684.Vb 7
685\& $h = start \e@cat, \e$in;
686\& $in = "line 1\en";
687\& pump $h;
688\& $in .= "line 2\en";
689\& pump $h;
690\& $in .= "line 3\en";
691\& finish $h;
692.Ve
693.PP
694The final call to \fIfinish()\fR must be there: it allows the child process(es)
695to run to completion and waits for their exit values.
696.SH "OBSTINATE CHILDREN"
697.IX Header "OBSTINATE CHILDREN"
698Interactive applications are usually optimized for human use. This
699can help or hinder trying to interact with them through modules like
700IPC::Run. Frequently, programs alter their behavior when they detect
701that stdin, stdout, or stderr are not connected to a tty, assuming that
702they are being run in batch mode. Whether this helps or hurts depends
703on which optimizations change. And there's often no way of telling
704what a program does in these areas other than trial and error and,
705occasionally, reading the source. This includes different versions
706and implementations of the same program.
707.PP
708All hope is not lost, however. Most programs behave in reasonably
709tractable manners, once you figure out what it's trying to do.
710.PP
711Here are some of the issues you might need to be aware of.
712.IP "\(bu" 4
713\&\fIfflush()\fRing stdout and stderr
714.Sp
715This lets the user see stdout and stderr immediately. Many programs
716undo this optimization if stdout is not a tty, making them harder to
717manage by things like IPC::Run.
718.Sp
719Many programs decline to fflush stdout or stderr if they do not
720detect a tty there. Some ftp commands do this, for instance.
721.Sp
722If this happens to you, look for a way to force interactive behavior,
723like a command line switch or command. If you can't, you will
724need to use a pseudo terminal ('<pty<' and '>pty>').
725.IP "\(bu" 4
726false prompts
727.Sp
728Interactive programs generally do not guarantee that output from user
729commands won't contain a prompt string. For example, your shell prompt
730might be a '$', and a file named '$' might be the only file in a directory
731listing.
732.Sp
733This can make it hard to guarantee that your output parser won't be fooled
734into early termination of results.
735.Sp
736To help work around this, you can see if the program can alter it's
737prompt, and use something you feel is never going to occur in actual
738practice.
739.Sp
740You should also look for your prompt to be the only thing on a line:
741.Sp
742.Vb 1
743\& pump $h until $out =~ /^<SILLYPROMPT>\es?\ez/m;
744.Ve
745.Sp
746(use \f(CW\*(C`(?!\en)\eZ\*(C'\fR in place of \f(CW\*(C`\ez\*(C'\fR on older perls).
747.Sp
748You can also take the approach that IPC::ChildSafe takes and emit a
749command with known output after each 'real' command you issue, then
750look for this known output. See \fInew_appender()\fR and \fInew_chunker()\fR for
751filters that can help with this task.
752.Sp
753If it's not convenient or possibly to alter a prompt or use a known
754command/response pair, you might need to autodetect the prompt in case
755the local version of the child program is different then the one
756you tested with, or if the user has control over the look & feel of
757the prompt.
758.IP "\(bu" 4
759Refusing to accept input unless stdin is a tty.
760.Sp
761Some programs, for security reasons, will only accept certain types
762of input from a tty. su, notable, will not prompt for a password unless
763it's connected to a tty.
764.Sp
765If this is your situation, use a pseudo terminal ('<pty<' and '>pty>').
766.IP "\(bu" 4
767Not prompting unless connected to a tty.
768.Sp
769Some programs don't prompt unless stdin or stdout is a tty. See if you can
770turn prompting back on. If not, see if you can come up with a command that
771you can issue after every real command and look for it's output, as
772IPC::ChildSafe does. There are two filters included with IPC::Run that
773can help with doing this: appender and chunker (see \fInew_appender()\fR and
774\&\fInew_chunker()\fR).
775.IP "\(bu" 4
776Different output format when not connected to a tty.
777.Sp
778Some commands alter their formats to ease machine parsability when they
779aren't connected to a pipe. This is actually good, but can be surprising.
780.SH "PSEUDO TERMINALS"
781.IX Header "PSEUDO TERMINALS"
782On systems providing pseudo terminals under /dev, IPC::Run can use IO::Pty
783(available on \s-1CPAN\s0) to provide a terminal environment to subprocesses.
784This is necessary when the subprocess really wants to think it's connected
785to a real terminal.
786.SS "\s-1CAVEATS\s0"
787.IX Subsection "CAVEATS"
788Psuedo-terminals are not pipes, though they are similar. Here are some
789differences to watch out for.
790.IP "Echoing" 4
791.IX Item "Echoing"
792Sending to stdin will cause an echo on stdout, which occurs before each
793line is passed to the child program. There is currently no way to
794disable this, although the child process can and should disable it for
795things like passwords.
796.IP "Shutdown" 4
797.IX Item "Shutdown"
798IPC::Run cannot close a pty until all output has been collected. This
799means that it is not possible to send an \s-1EOF\s0 to stdin by half-closing
800the pty, as we can when using a pipe to stdin.
801.Sp
802This means that you need to send the child process an exit command or
803signal, or \fIrun()\fR / \fIfinish()\fR will time out. Be careful not to expect a
804prompt after sending the exit command.
805.IP "Command line editing" 4
806.IX Item "Command line editing"
807Some subprocesses, notable shells that depend on the user's prompt
808settings, will reissue the prompt plus the command line input so far
809once for each character.
810.IP "'>pty>' means '&>pty>', not '1>pty>'" 4
811.IX Item "'>pty>' means '&>pty>', not '1>pty>'"
812The pseudo terminal redirects both stdout and stderr unless you specify
813a file descriptor. If you want to grab stderr separately, do this:
814.Sp
815.Vb 1
816\& start \e@cmd, \*(Aq<pty<\*(Aq, \e$in, \*(Aq>pty>\*(Aq, \e$out, \*(Aq2>\*(Aq, \e$err;
817.Ve
818.IP "stdin, stdout, and stderr not inherited" 4
819.IX Item "stdin, stdout, and stderr not inherited"
820Child processes harnessed to a pseudo terminal have their stdin, stdout,
821and stderr completely closed before any redirection operators take
822effect. This casts of the bonds of the controlling terminal. This is
823not done when using pipes.
824.Sp
825Right now, this affects all children in a harness that has a pty in use,
826even if that pty would not affect a particular child. That's a bug and
827will be fixed. Until it is, it's best not to mix-and-match children.
828.SS "Redirection Operators"
829.IX Subsection "Redirection Operators"
830.Vb 3
831\& Operator SHNP Description
832\& ======== ==== ===========
833\& <, N< SHN Redirects input to a child\*(Aqs fd N (0 assumed)
834\&
835\& >, N> SHN Redirects output from a child\*(Aqs fd N (1 assumed)
836\& >>, N>> SHN Like \*(Aq>\*(Aq, but appends to scalars or named files
837\& >&, &> SHN Redirects stdout & stderr from a child process
838\&
839\& <pty, N<pty S Like \*(Aq<\*(Aq, but uses a pseudo\-tty instead of a pipe
840\& >pty, N>pty S Like \*(Aq>\*(Aq, but uses a pseudo\-tty instead of a pipe
841\&
842\& N<&M Dups input fd N to input fd M
843\& M>&N Dups output fd N to input fd M
844\& N<&\- Closes fd N
845\&
846\& <pipe, N<pipe P Pipe opens H for caller to read, write, close.
847\& >pipe, N>pipe P Pipe opens H for caller to read, write, close.
848.Ve
849.PP
850\&'N' and 'M' are placeholders for integer file descriptor numbers. The
851terms 'input' and 'output' are from the child process's perspective.
852.PP
853The \s-1SHNP\s0 field indicates what parameters an operator can take:
854.PP
855.Vb 6
856\& S: \e$scalar or \e&function references. Filters may be used with
857\& these operators (and only these).
858\& H: \e*HANDLE or IO::Handle for caller to open, and close
859\& N: "file name".
860\& P: \e*HANDLE opened by IPC::Run as the parent end of a pipe, but read
861\& and written to and closed by the caller (like IPC::Open3).
862.Ve
863.IP "Redirecting input: [n]<, [n]<pipe" 4
864.IX Item "Redirecting input: [n]<, [n]<pipe"
865You can input the child reads on file descriptor number n to come from a
866scalar variable, subroutine, file handle, or a named file. If stdin
867is not redirected, the parent's stdin is inherited.
868.Sp
869.Vb 2
870\& run \e@cat, \eundef ## Closes child\*(Aqs stdin immediately
871\& or die "cat returned $?";
872\&
873\& run \e@cat, \e$in;
874\&
875\& run \e@cat, \e<<TOHERE;
876\& blah
877\& TOHERE
878\&
879\& run \e@cat, \e&input; ## Calls &input, feeding data returned
880\& ## to child\*(Aqs. Closes child\*(Aqs stdin
881\& ## when undef is returned.
882.Ve
883.Sp
884Redirecting from named files requires you to use the input
885redirection operator:
886.Sp
887.Vb 2
888\& run \e@cat, \*(Aq<.profile\*(Aq;
889\& run \e@cat, \*(Aq<\*(Aq, \*(Aq.profile\*(Aq;
890\&
891\& open IN, "<foo";
892\& run \e@cat, \e*IN;
893\& run \e@cat, *IN{IO};
894.Ve
895.Sp
896The form used second example here is the safest,
897since filenames like \*(L"0\*(R" and \*(L"&more\en\*(R" won't confuse &run:
898.Sp
899You can't do either of
900.Sp
901.Vb 2
902\& run \e@a, *IN; ## INVALID
903\& run \e@a, \*(Aq<\*(Aq, *IN; ## BUGGY: Reads file named like "*main::A"
904.Ve
905.Sp
906because perl passes a scalar containing a string that
907looks like \*(L"*main::A\*(R" to &run, and &run can't tell the difference
908between that and a redirection operator or a file name. &run guarantees
909that any scalar you pass after a redirection operator is a file name.
910.Sp
911If your child process will take input from file descriptors other
912than 0 (stdin), you can use a redirection operator with any of the
913valid input forms (scalar ref, sub ref, etc.):
914.Sp
915.Vb 1
916\& run \e@cat, \*(Aq3<\*(Aq, \e$in3;
917.Ve
918.Sp
919When redirecting input from a scalar ref, the scalar ref is
920used as a queue. This allows you to use &harness and \fIpump()\fR to
921feed incremental bits of input to a coprocess. See \*(L"Coprocesses\*(R"
922below for more information.
923.Sp
924The <pipe operator opens the write half of a pipe on the filehandle
925glob reference it takes as an argument:
926.Sp
927.Vb 5
928\& $h = start \e@cat, \*(Aq<pipe\*(Aq, \e*IN;
929\& print IN "hello world\en";
930\& pump $h;
931\& close IN;
932\& finish $h;
933.Ve
934.Sp
935Unlike the other '<' operators, IPC::Run does nothing further with
936it: you are responsible for it. The previous example is functionally
937equivalent to:
938.Sp
939.Vb 6
940\& pipe( \e*R, \e*IN ) or die $!;
941\& $h = start \e@cat, \*(Aq<\*(Aq, \e*IN;
942\& print IN "hello world\en";
943\& pump $h;
944\& close IN;
945\& finish $h;
946.Ve
947.Sp
948This is like the behavior of IPC::Open2 and IPC::Open3.
949.Sp
950\&\fBWin32\fR: The handle returned is actually a socket handle, so you can
951use \fIselect()\fR on it.
952.IP "Redirecting output: [n]>, [n]>>, [n]>&[m], [n]>pipe" 4
953.IX Item "Redirecting output: [n]>, [n]>>, [n]>&[m], [n]>pipe"
954You can redirect any output the child emits
955to a scalar variable, subroutine, file handle, or file name. You
956can have &run truncate or append to named files or scalars. If
957you are redirecting stdin as well, or if the command is on the
958receiving end of a pipeline ('|'), you can omit the redirection
959operator:
960.Sp
961.Vb 3
962\& @ls = ( \*(Aqls\*(Aq );
963\& run \e@ls, \eundef, \e$out
964\& or die "ls returned $?";
965\&
966\& run \e@ls, \eundef, \e&out; ## Calls &out each time some output
967\& ## is received from the child\*(Aqs
968\& ## when undef is returned.
969\&
970\& run \e@ls, \eundef, \*(Aq2>ls.err\*(Aq;
971\& run \e@ls, \*(Aq2>\*(Aq, \*(Aqls.err\*(Aq;
972.Ve
973.Sp
974The two parameter form guarantees that the filename
975will not be interpreted as a redirection operator:
976.Sp
977.Vb 2
978\& run \e@ls, \*(Aq>\*(Aq, "&more";
979\& run \e@ls, \*(Aq2>\*(Aq, ">foo\en";
980.Ve
981.Sp
982You can pass file handles you've opened for writing:
983.Sp
984.Vb 3
985\& open( *OUT, ">out.txt" );
986\& open( *ERR, ">err.txt" );
987\& run \e@cat, \e*OUT, \e*ERR;
988.Ve
989.Sp
990Passing a scalar reference and a code reference requires a little
991more work, but allows you to capture all of the output in a scalar
992or each piece of output by a callback:
993.Sp
994These two do the same things:
995.Sp
996.Vb 1
997\& run( [ \*(Aqls\*(Aq ], \*(Aq2>\*(Aq, sub { $err_out .= $_[0] } );
998.Ve
999.Sp
1000does the same basic thing as:
1001.Sp
1002.Vb 1
1003\& run( [ \*(Aqls\*(Aq ], \*(Aq2>\*(Aq, \e$err_out );
1004.Ve
1005.Sp
1006The subroutine will be called each time some data is read from the child.
1007.Sp
1008The >pipe operator is different in concept than the other '>' operators,
1009although it's syntax is similar:
1010.Sp
1011.Vb 7
1012\& $h = start \e@cat, $in, \*(Aq>pipe\*(Aq, \e*OUT, \*(Aq2>pipe\*(Aq, \e*ERR;
1013\& $in = "hello world\en";
1014\& finish $h;
1015\& print <OUT>;
1016\& print <ERR>;
1017\& close OUT;
1018\& close ERR;
1019.Ve
1020.Sp
1021causes two pipe to be created, with one end attached to cat's stdout
1022and stderr, respectively, and the other left open on \s-1OUT\s0 and \s-1ERR\s0, so
1023that the script can manually
1024\&\fIread()\fR, \fIselect()\fR, etc. on them. This is like
1025the behavior of IPC::Open2 and IPC::Open3.
1026.Sp
1027\&\fBWin32\fR: The handle returned is actually a socket handle, so you can
1028use \fIselect()\fR on it.
1029.IP "Duplicating output descriptors: >&m, n>&m" 4
1030.IX Item "Duplicating output descriptors: >&m, n>&m"
1031This duplicates output descriptor number n (default is 1 if n is omitted)
1032from descriptor number m.
1033.IP "Duplicating input descriptors: <&m, n<&m" 4
1034.IX Item "Duplicating input descriptors: <&m, n<&m"
1035This duplicates input descriptor number n (default is 0 if n is omitted)
1036from descriptor number m
1037.IP "Closing descriptors: <&\-, 3<&\-" 4
1038.IX Item "Closing descriptors: <&-, 3<&-"
1039This closes descriptor number n (default is 0 if n is omitted). The
1040following commands are equivalent:
1041.Sp
1042.Vb 3
1043\& run \e@cmd, \eundef;
1044\& run \e@cmd, \*(Aq<&\-\*(Aq;
1045\& run \e@cmd, \*(Aq<in.txt\*(Aq, \*(Aq<&\-\*(Aq;
1046.Ve
1047.Sp
1048Doing
1049.Sp
1050.Vb 1
1051\& run \e@cmd, \e$in, \*(Aq<&\-\*(Aq; ## SIGPIPE recipe.
1052.Ve
1053.Sp
1054is dangerous: the parent will get a \s-1SIGPIPE\s0 if \f(CW$in\fR is not empty.
1055.IP "Redirecting both stdout and stderr: &>, >&, &>pipe, >pipe&" 4
1056.IX Item "Redirecting both stdout and stderr: &>, >&, &>pipe, >pipe&"
1057The following pairs of commands are equivalent:
1058.Sp
1059.Vb 2
1060\& run \e@cmd, \*(Aq>&\*(Aq, \e$out; run \e@cmd, \*(Aq>\*(Aq, \e$out, \*(Aq2>&1\*(Aq;
1061\& run \e@cmd, \*(Aq>&\*(Aq, \*(Aqout.txt\*(Aq; run \e@cmd, \*(Aq>\*(Aq, \*(Aqout.txt\*(Aq, \*(Aq2>&1\*(Aq;
1062.Ve
1063.Sp
1064etc.
1065.Sp
1066File descriptor numbers are not permitted to the left or the right of
1067these operators, and the '&' may occur on either end of the operator.
1068.Sp
1069The '&>pipe' and '>pipe&' variants behave like the '>pipe' operator, except
1070that both stdout and stderr write to the created pipe.
1071.IP "Redirection Filters" 4
1072.IX Item "Redirection Filters"
1073Both input redirections and output redirections that use scalars or
1074subs as endpoints may have an arbitrary number of filter subs placed
1075between them and the child process. This is useful if you want to
1076receive output in chunks, or if you want to massage each chunk of
1077data sent to the child. To use this feature, you must use operator
1078syntax:
1079.Sp
1080.Vb 5
1081\& run(
1082\& \e@cmd
1083\& \*(Aq<\*(Aq, \e&in_filter_2, \e&in_filter_1, $in,
1084\& \*(Aq>\*(Aq, \e&out_filter_1, \e&in_filter_2, $out,
1085\& );
1086.Ve
1087.Sp
1088This capability is not provided for \s-1IO\s0 handles or named files.
1089.Sp
1090Two filters are provided by IPC::Run: appender and chunker. Because
1091these may take an argument, you need to use the constructor functions
1092\&\fInew_appender()\fR and \fInew_chunker()\fR rather than using \e& syntax:
1093.Sp
1094.Vb 5
1095\& run(
1096\& \e@cmd
1097\& \*(Aq<\*(Aq, new_appender( "\en" ), $in,
1098\& \*(Aq>\*(Aq, new_chunker, $out,
1099\& );
1100.Ve
1101.SS "Just doing I/O"
1102.IX Subsection "Just doing I/O"
1103If you just want to do I/O to a handle or file you open yourself, you
1104may specify a filehandle or filename instead of a command in the harness
1105specification:
1106.PP
1107.Vb 1
1108\& run io( "filename", \*(Aq>\*(Aq, \e$recv );
1109\&
1110\& $h = start io( $io, \*(Aq>\*(Aq, \e$recv );
1111\&
1112\& $h = harness \e@cmd, \*(Aq&\*(Aq, io( "file", \*(Aq<\*(Aq, \e$send );
1113.Ve
1114.SS "Options"
1115.IX Subsection "Options"
1116Options are passed in as name/value pairs:
1117.PP
1118.Vb 1
1119\& run \e@cat, \e$in, debug => 1;
1120.Ve
1121.PP
1122If you pass the debug option, you may want to pass it in first, so you
1123can see what parsing is going on:
1124.PP
1125.Vb 1
1126\& run debug => 1, \e@cat, \e$in;
1127.Ve
1128.IP "debug" 4
1129.IX Item "debug"
1130Enables debugging output in parent and child. Debugging info is emitted
1131to the \s-1STDERR\s0 that was present when IPC::Run was first \f(CW\*(C`use()\*(C'\fRed (it's
1132\&\f(CW\*(C`dup()\*(C'\fRed out of the way so that it can be redirected in children without
1133having debugging output emitted on it).
1134.SH "RETURN VALUES"
1135.IX Header "RETURN VALUES"
1136\&\fIharness()\fR and \fIstart()\fR return a reference to an IPC::Run harness. This is
1137blessed in to the IPC::Run package, so you may make later calls to
1138functions as members if you like:
1139.PP
1140.Vb 4
1141\& $h = harness( ... );
1142\& $h\->start;
1143\& $h\->pump;
1144\& $h\->finish;
1145\&
1146\& $h = start( .... );
1147\& $h\->pump;
1148\& ...
1149.Ve
1150.PP
1151Of course, using method call syntax lets you deal with any IPC::Run
1152subclasses that might crop up, but don't hold your breath waiting for
1153any.
1154.PP
1155\&\fIrun()\fR and \fIfinish()\fR return \s-1TRUE\s0 when all subcommands exit with a 0 result
1156code. \fBThis is the opposite of perl's \f(BIsystem()\fB command\fR.
1157.PP
1158All routines raise exceptions (via \fIdie()\fR) when error conditions are
1159recognized. A non-zero command result is not treated as an error
1160condition, since some commands are tests whose results are reported
1161in their exit codes.
1162.SH "ROUTINES"
1163.IX Header "ROUTINES"
1164.IP "run" 4
1165.IX Item "run"
1166Run takes a harness or harness specification and runs it, pumping
1167all input to the child(ren), closing the input pipes when no more
1168input is available, collecting all output that arrives, until the
1169pipes delivering output are closed, then waiting for the children to
1170exit and reaping their result codes.
1171.Sp
1172You may think of \f(CW\*(C`run( ... )\*(C'\fR as being like
1173.Sp
1174.Vb 1
1175\& start( ... )\->finish();
1176.Ve
1177.Sp
1178, though there is one subtle difference: \fIrun()\fR does not
1179set \e$input_scalars to '' like \fIfinish()\fR does. If an exception is thrown
1180from \fIrun()\fR, all children will be killed off \*(L"gently\*(R", and then \*(L"annihilated\*(R"
1181if they do not go gently (in to that dark night. sorry).
1182.Sp
1183If any exceptions are thrown, this does a \*(L"kill_kill\*(R" before propogating
1184them.
1185.IP "signal" 4
1186.IX Item "signal"
1187.Vb 3
1188\& ## To send it a specific signal by name ("USR1"):
1189\& signal $h, "USR1";
1190\& $h\->signal ( "USR1" );
1191.Ve
1192.Sp
1193If \f(CW$signal\fR is provided and defined, sends a signal to all child processes. Try
1194not to send numeric signals, use \f(CW"KILL"\fR instead of \f(CW9\fR, for instance.
1195Numeric signals aren't portable.
1196.Sp
1197Throws an exception if \f(CW$signal\fR is undef.
1198.Sp
1199This will \fInot\fR clean up the harness, \f(CW\*(C`finish\*(C'\fR it if you kill it.
1200.Sp
1201Normally \s-1TERM\s0 kills a process gracefully (this is what the command line utility
1202\&\f(CW\*(C`kill\*(C'\fR does by default), \s-1INT\s0 is sent by one of the keys \f(CW\*(C`^C\*(C'\fR, \f(CW\*(C`Backspace\*(C'\fR or
1203\&\f(CW\*(C`<Del>\*(C'\fR, and \f(CW\*(C`QUIT\*(C'\fR is used to kill a process and make it coredump.
1204.Sp
1205The \f(CW\*(C`HUP\*(C'\fR signal is often used to get a process to \*(L"restart\*(R", rereading
1206config files, and \f(CW\*(C`USR1\*(C'\fR and \f(CW\*(C`USR2\*(C'\fR for really application-specific things.
1207.Sp
1208Often, running \f(CW\*(C`kill \-l\*(C'\fR (that's a lower case \*(L"L\*(R") on the command line will
1209list the signals present on your operating system.
1210.Sp
1211\&\fB\s-1WARNING\s0\fR: The signal subsystem is not at all portable. We *may* offer
1212to simulate \f(CW\*(C`TERM\*(C'\fR and \f(CW\*(C`KILL\*(C'\fR on some operating systems, submit code
1213to me if you want this.
1214.Sp
1215\&\fB\s-1WARNING\s0 2\fR: Up to and including perl v5.6.1, doing almost anything in a
1216signal handler could be dangerous. The most safe code avoids all
1217mallocs and system calls, usually by preallocating a flag before
1218entering the signal handler, altering the flag's value in the
1219handler, and responding to the changed value in the main system:
1220.Sp
1221.Vb 2
1222\& my $got_usr1 = 0;
1223\& sub usr1_handler { ++$got_signal }
1224\&
1225\& $SIG{USR1} = \e&usr1_handler;
1226\& while () { sleep 1; print "GOT IT" while $got_usr1\-\-; }
1227.Ve
1228.Sp
1229Even this approach is perilous if ++ and \*(-- aren't atomic on your system
1230(I've never heard of this on any modern \s-1CPU\s0 large enough to run perl).
1231.IP "kill_kill" 4
1232.IX Item "kill_kill"
1233.Vb 3
1234\& ## To kill off a process:
1235\& $h\->kill_kill;
1236\& kill_kill $h;
1237\&
1238\& ## To specify the grace period other than 30 seconds:
1239\& kill_kill $h, grace => 5;
1240\&
1241\& ## To send QUIT instead of KILL if a process refuses to die:
1242\& kill_kill $h, coup_d_grace => "QUIT";
1243.Ve
1244.Sp
1245Sends a \f(CW\*(C`TERM\*(C'\fR, waits for all children to exit for up to 30 seconds, then
1246sends a \f(CW\*(C`KILL\*(C'\fR to any that survived the \f(CW\*(C`TERM\*(C'\fR.
1247.Sp
1248Will wait for up to 30 more seconds for the \s-1OS\s0 to sucessfully \f(CW\*(C`KILL\*(C'\fR the
1249processes.
1250.Sp
1251The 30 seconds may be overriden by setting the \f(CW\*(C`grace\*(C'\fR option, this
1252overrides both timers.
1253.Sp
1254The harness is then cleaned up.
1255.Sp
1256The doubled name indicates that this function may kill again and avoids
1257colliding with the core Perl \f(CW\*(C`kill\*(C'\fR function.
1258.Sp
1259Returns a 1 if the \f(CW\*(C`TERM\*(C'\fR was sufficient, or a 0 if \f(CW\*(C`KILL\*(C'\fR was
1260required. Throws an exception if \f(CW\*(C`KILL\*(C'\fR did not permit the children
1261to be reaped.
1262.Sp
1263\&\fB\s-1NOTE\s0\fR: The grace period is actually up to 1 second longer than that
1264given. This is because the granularity of \f(CW\*(C`time\*(C'\fR is 1 second. Let me
1265know if you need finer granularity, we can leverage Time::HiRes here.
1266.Sp
1267\&\fBWin32\fR: Win32 does not know how to send real signals, so \f(CW\*(C`TERM\*(C'\fR is
1268a full-force kill on Win32. Thus all talk of grace periods, etc. do
1269not apply to Win32.
1270.IP "harness" 4
1271.IX Item "harness"
1272Takes a harness specification and returns a harness. This harness is
1273blessed in to IPC::Run, allowing you to use method call syntax for
1274\&\fIrun()\fR, \fIstart()\fR, et al if you like.
1275.Sp
1276\&\fIharness()\fR is provided so that you can pre-build harnesses if you
1277would like to, but it's not required..
1278.Sp
1279You may proceed to \fIrun()\fR, \fIstart()\fR or \fIpump()\fR after calling \fIharness()\fR (\fIpump()\fR
1280calls \fIstart()\fR if need be). Alternatively, you may pass your
1281harness specification to \fIrun()\fR or \fIstart()\fR and let them \fIharness()\fR for
1282you. You can't pass harness specifications to \fIpump()\fR, though.
1283.IP "close_terminal" 4
1284.IX Item "close_terminal"
1285This is used as (or in) an init sub to cast off the bonds of a controlling
1286terminal. It must precede all other redirection ops that affect
1287\&\s-1STDIN\s0, \s-1STDOUT\s0, or \s-1STDERR\s0 to be guaranteed effective.
1288.IP "start" 4
1289.IX Item "start"
1290.Vb 5
1291\& $h = start(
1292\& \e@cmd, \e$in, \e$out, ...,
1293\& timeout( 30, name => "process timeout" ),
1294\& $stall_timeout = timeout( 10, name => "stall timeout" ),
1295\& );
1296\&
1297\& $h = start \e@cmd, \*(Aq<\*(Aq, \e$in, \*(Aq|\*(Aq, \e@cmd2, ...;
1298.Ve
1299.Sp
1300\&\fIstart()\fR accepts a harness or harness specification and returns a harness
1301after building all of the pipes and launching (via \fIfork()\fR/\fIexec()\fR, or, maybe
1302someday, \fIspawn()\fR) all the child processes. It does not send or receive any
1303data on the pipes, see \fIpump()\fR and \fIfinish()\fR for that.
1304.Sp
1305You may call \fIharness()\fR and then pass it's result to \fIstart()\fR if you like,
1306but you only need to if it helps you structure or tune your application.
1307If you do call \fIharness()\fR, you may skip \fIstart()\fR and proceed directly to
1308pump.
1309.Sp
1310\&\fIstart()\fR also starts all timers in the harness. See IPC::Run::Timer
1311for more information.
1312.Sp
1313\&\fIstart()\fR flushes \s-1STDOUT\s0 and \s-1STDERR\s0 to help you avoid duplicate output.
1314It has no way of asking Perl to flush all your open filehandles, so
1315you are going to need to flush any others you have open. Sorry.
1316.Sp
1317Here's how if you don't want to alter the state of $| for your
1318filehandle:
1319.Sp
1320.Vb 1
1321\& $ofh = select HANDLE; $of = $|; $| = 1; $| = $of; select $ofh;
1322.Ve
1323.Sp
1324If you don't mind leaving output unbuffered on \s-1HANDLE\s0, you can do
1325the slightly shorter
1326.Sp
1327.Vb 1
1328\& $ofh = select HANDLE; $| = 1; select $ofh;
1329.Ve
1330.Sp
1331Or, you can use IO::Handle's \fIflush()\fR method:
1332.Sp
1333.Vb 2
1334\& use IO::Handle;
1335\& flush HANDLE;
1336.Ve
1337.Sp
1338Perl needs the equivalent of C's fflush( (\s-1FILE\s0 *)NULL ).
1339.IP "pump" 4
1340.IX Item "pump"
1341.Vb 2
1342\& pump $h;
1343\& $h\->pump;
1344.Ve
1345.Sp
1346Pump accepts a single parameter harness. It blocks until it delivers some
1347input or recieves some output. It returns \s-1TRUE\s0 if there is still input or
1348output to be done, \s-1FALSE\s0 otherwise.
1349.Sp
1350\&\fIpump()\fR will automatically call \fIstart()\fR if need be, so you may call \fIharness()\fR
1351then proceed to \fIpump()\fR if that helps you structure your application.
1352.Sp
1353If \fIpump()\fR is called after all harnessed activities have completed, a \*(L"process
1354ended prematurely\*(R" exception to be thrown. This allows for simple scripting
1355of external applications without having to add lots of error handling code at
1356each step of the script:
1357.Sp
1358.Vb 1
1359\& $h = harness \e@smbclient, \e$in, \e$out, $err;
1360\&
1361\& $in = "cd /foo\en";
1362\& $h\->pump until $out =~ /^smb.*> \eZ/m;
1363\& die "error cding to /foo:\en$out" if $out =~ "ERR";
1364\& $out = \*(Aq\*(Aq;
1365\&
1366\& $in = "mget *\en";
1367\& $h\->pump until $out =~ /^smb.*> \eZ/m;
1368\& die "error retrieving files:\en$out" if $out =~ "ERR";
1369\&
1370\& $h\->finish;
1371\&
1372\& warn $err if $err;
1373.Ve
1374.IP "pump_nb" 4
1375.IX Item "pump_nb"
1376.Vb 2
1377\& pump_nb $h;
1378\& $h\->pump_nb;
1379.Ve
1380.Sp
1381\&\*(L"\fIpump()\fR non-blocking\*(R", pumps if anything's ready to be pumped, returns
1382immediately otherwise. This is useful if you're doing some long-running
1383task in the foreground, but don't want to starve any child processes.
1384.IP "pumpable" 4
1385.IX Item "pumpable"
1386Returns \s-1TRUE\s0 if calling \fIpump()\fR won't throw an immediate \*(L"process ended
1387prematurely\*(R" exception. This means that there are open I/O channels or
1388active processes. May yield the parent processes' time slice for 0.01
1389second if all pipes are to the child and all are paused. In this case
1390we can't tell if the child is dead, so we yield the processor and
1391then attempt to reap the child in a nonblocking way.
1392.IP "reap_nb" 4
1393.IX Item "reap_nb"
1394Attempts to reap child processes, but does not block.
1395.Sp
1396Does not currently take any parameters, one day it will allow specific
1397children to be reaped.
1398.Sp
1399Only call this from a signal handler if your \f(CW\*(C`perl\*(C'\fR is recent enough
1400to have safe signal handling (5.6.1 did not, \s-1IIRC\s0, but it was beign discussed
1401on perl5\-porters). Calling this (or doing any significant work) in a signal
1402handler on older \f(CW\*(C`perl\*(C'\fRs is asking for seg faults.
1403.IP "finish" 4
1404.IX Item "finish"
1405This must be called after the last \fIstart()\fR or \fIpump()\fR call for a harness,
1406or your system will accumulate defunct processes and you may \*(L"leak\*(R"
1407file descriptors.
1408.Sp
1409\&\fIfinish()\fR returns \s-1TRUE\s0 if all children returned 0 (and were not signaled and did
1410not coredump, ie ! $?), and \s-1FALSE\s0 otherwise (this is like \fIrun()\fR, and the
1411opposite of \fIsystem()\fR).
1412.Sp
1413Once a harness has been finished, it may be \fIrun()\fR or \fIstart()\fRed again,
1414including by \fIpump()\fRs auto-start.
1415.Sp
1416If this throws an exception rather than a normal exit, the harness may
1417be left in an unstable state, it's best to kill the harness to get rid
1418of all the child processes, etc.
1419.Sp
1420Specifically, if a timeout expires in \fIfinish()\fR, \fIfinish()\fR will not
1421kill all the children. Call \f(CW\*(C`<$h\-\*(C'\fRkill_kill>> in this case if you care.
1422This differs from the behavior of \*(L"run\*(R".
1423.IP "result" 4
1424.IX Item "result"
1425.Vb 1
1426\& $h\->result;
1427.Ve
1428.Sp
1429Returns the first non-zero result code (ie $? >> 8). See \*(L"full_result\*(R" to
1430get the $? value for a child process.
1431.Sp
1432To get the result of a particular child, do:
1433.Sp
1434.Vb 2
1435\& $h\->result( 0 ); # first child\*(Aqs $? >> 8
1436\& $h\->result( 1 ); # second child
1437.Ve
1438.Sp
1439or
1440.Sp
1441.Vb 2
1442\& ($h\->results)[0]
1443\& ($h\->results)[1]
1444.Ve
1445.Sp
1446Returns undef if no child processes were spawned and no child number was
1447specified. Throws an exception if an out-of-range child number is passed.
1448.IP "results" 4
1449.IX Item "results"
1450Returns a list of child exit values. See \*(L"full_results\*(R" if you want to
1451know if a signal killed the child.
1452.Sp
1453Throws an exception if the harness is not in a finished state.
1454.IP "full_result" 4
1455.IX Item "full_result"
1456.Vb 1
1457\& $h\->full_result;
1458.Ve
1459.Sp
1460Returns the first non-zero $?. See \*(L"result\*(R" to get the first $? >> 8
1461value for a child process.
1462.Sp
1463To get the result of a particular child, do:
1464.Sp
1465.Vb 2
1466\& $h\->full_result( 0 ); # first child\*(Aqs $? >> 8
1467\& $h\->full_result( 1 ); # second child
1468.Ve
1469.Sp
1470or
1471.Sp
1472.Vb 2
1473\& ($h\->full_results)[0]
1474\& ($h\->full_results)[1]
1475.Ve
1476.Sp
1477Returns undef if no child processes were spawned and no child number was
1478specified. Throws an exception if an out-of-range child number is passed.
1479.IP "full_results" 4
1480.IX Item "full_results"
1481Returns a list of child exit values as returned by \f(CW\*(C`wait\*(C'\fR. See \*(L"results\*(R"
1482if you don't care about coredumps or signals.
1483.Sp
1484Throws an exception if the harness is not in a finished state.
1485.SH "FILTERS"
1486.IX Header "FILTERS"
1487These filters are used to modify input our output between a child
1488process and a scalar or subroutine endpoint.
1489.IP "binary" 4
1490.IX Item "binary"
1491.Vb 3
1492\& run \e@cmd, ">", binary, \e$out;
1493\& run \e@cmd, ">", binary, \e$out; ## Any TRUE value to enable
1494\& run \e@cmd, ">", binary 0, \e$out; ## Any FALSE value to disable
1495.Ve
1496.Sp
1497This is a constructor for a \*(L"binmode\*(R" \*(L"filter\*(R" that tells IPC::Run to keep
1498the carriage returns that would ordinarily be edited out for you (binmode
1499is usually off). This is not a real filter, but an option masquerading as
1500a filter.
1501.Sp
1502It's not named \*(L"binmode\*(R" because you're likely to want to call Perl's binmode
1503in programs that are piping binary data around.
1504.IP "new_chunker" 4
1505.IX Item "new_chunker"
1506This breaks a stream of data in to chunks, based on an optional
1507scalar or regular expression parameter. The default is the Perl
1508input record separator in $/, which is a newline be default.
1509.Sp
1510.Vb 2
1511\& run \e@cmd, \*(Aq>\*(Aq, new_chunker, \e&lines_handler;
1512\& run \e@cmd, \*(Aq>\*(Aq, new_chunker( "\er\en" ), \e&lines_handler;
1513.Ve
1514.Sp
1515Because this uses $/ by default, you should always pass in a parameter
1516if you are worried about other code (modules, etc) modifying $/.
1517.Sp
1518If this filter is last in a filter chain that dumps in to a scalar,
1519the scalar must be set to '' before a new chunk will be written to it.
1520.Sp
1521As an example of how a filter like this can be written, here's a
1522chunker that splits on newlines:
1523.Sp
1524.Vb 2
1525\& sub line_splitter {
1526\& my ( $in_ref, $out_ref ) = @_;
1527\&
1528\& return 0 if length $$out_ref;
1529\&
1530\& return input_avail && do {
1531\& while (1) {
1532\& if ( $$in_ref =~ s/\eA(.*?\en)// ) {
1533\& $$out_ref .= $1;
1534\& return 1;
1535\& }
1536\& my $hmm = get_more_input;
1537\& unless ( defined $hmm ) {
1538\& $$out_ref = $$in_ref;
1539\& $$in_ref = \*(Aq\*(Aq;
1540\& return length $$out_ref ? 1 : 0;
1541\& }
1542\& return 0 if $hmm eq 0;
1543\& }
1544\& }
1545\& };
1546.Ve
1547.IP "new_appender" 4
1548.IX Item "new_appender"
1549This appends a fixed string to each chunk of data read from the source
1550scalar or sub. This might be useful if you're writing commands to a
1551child process that always must end in a fixed string, like \*(L"\en\*(R":
1552.Sp
1553.Vb 3
1554\& run( \e@cmd,
1555\& \*(Aq<\*(Aq, new_appender( "\en" ), \e&commands,
1556\& );
1557.Ve
1558.Sp
1559Here's a typical filter sub that might be created by \fInew_appender()\fR:
1560.Sp
1561.Vb 2
1562\& sub newline_appender {
1563\& my ( $in_ref, $out_ref ) = @_;
1564\&
1565\& return input_avail && do {
1566\& $$out_ref = join( \*(Aq\*(Aq, $$out_ref, $$in_ref, "\en" );
1567\& $$in_ref = \*(Aq\*(Aq;
1568\& 1;
1569\& }
1570\& };
1571.Ve
1572.IP "io" 4
1573.IX Item "io"
1574Takes a filename or filehandle, a redirection operator, optional filters,
1575and a source or destination (depends on the redirection operator). Returns
1576an IPC::Run::IO object suitable for \fIharness()\fRing (including via \fIstart()\fR
1577or \fIrun()\fR).
1578.Sp
1579This is shorthand for
1580.Sp
1581.Vb 1
1582\& require IPC::Run::IO;
1583\&
1584\& ... IPC::Run::IO\->new(...) ...
1585.Ve
1586.IP "timer" 4
1587.IX Item "timer"
1588.Vb 1
1589\& $h = start( \e@cmd, \e$in, \e$out, $t = timer( 5 ) );
1590\&
1591\& pump $h until $out =~ /expected stuff/ || $t\->is_expired;
1592.Ve
1593.Sp
1594Instantiates a non-fatal timer. \fIpump()\fR returns once each time a timer
1595expires. Has no direct effect on \fIrun()\fR, but you can pass a subroutine
1596to fire when the timer expires.
1597.Sp
1598See \*(L"timeout\*(R" for building timers that throw exceptions on
1599expiration.
1600.Sp
1601See \*(L"timer\*(R" in IPC::Run::Timer for details.
1602.IP "timeout" 4
1603.IX Item "timeout"
1604.Vb 1
1605\& $h = start( \e@cmd, \e$in, \e$out, $t = timeout( 5 ) );
1606\&
1607\& pump $h until $out =~ /expected stuff/;
1608.Ve
1609.Sp
1610Instantiates a timer that throws an exception when it expires.
1611If you don't provide an exception, a default exception that matches
1612/^IPC::Run: .*timed out/ is thrown by default. You can pass in your own
1613exception scalar or reference:
1614.Sp
1615.Vb 4
1616\& $h = start(
1617\& \e@cmd, \e$in, \e$out,
1618\& $t = timeout( 5, exception => \*(Aqslowpoke\*(Aq ),
1619\& );
1620.Ve
1621.Sp
1622or set the name used in debugging message and in the default exception
1623string:
1624.Sp
1625.Vb 5
1626\& $h = start(
1627\& \e@cmd, \e$in, \e$out,
1628\& timeout( 50, name => \*(Aqprocess timer\*(Aq ),
1629\& $stall_timer = timeout( 5, name => \*(Aqstall timer\*(Aq ),
1630\& );
1631\&
1632\& pump $h until $out =~ /started/;
1633\&
1634\& $in = \*(Aqcommand 1\*(Aq;
1635\& $stall_timer\->start;
1636\& pump $h until $out =~ /command 1 finished/;
1637\&
1638\& $in = \*(Aqcommand 2\*(Aq;
1639\& $stall_timer\->start;
1640\& pump $h until $out =~ /command 2 finished/;
1641\&
1642\& $in = \*(Aqvery slow command 3\*(Aq;
1643\& $stall_timer\->start( 10 );
1644\& pump $h until $out =~ /command 3 finished/;
1645\&
1646\& $stall_timer\->start( 5 );
1647\& $in = \*(Aqcommand 4\*(Aq;
1648\& pump $h until $out =~ /command 4 finished/;
1649\&
1650\& $stall_timer\->reset; # Prevent restarting or expirng
1651\& finish $h;
1652.Ve
1653.Sp
1654See \*(L"timer\*(R" for building non-fatal timers.
1655.Sp
1656See \*(L"timer\*(R" in IPC::Run::Timer for details.
1657.SH "FILTER IMPLEMENTATION FUNCTIONS"
1658.IX Header "FILTER IMPLEMENTATION FUNCTIONS"
1659These functions are for use from within filters.
1660.IP "input_avail" 4
1661.IX Item "input_avail"
1662Returns \s-1TRUE\s0 if input is available. If none is available, then
1663&get_more_input is called and its result is returned.
1664.Sp
1665This is usually used in preference to &get_more_input so that the
1666calling filter removes all data from the \f(CW$in_ref\fR before more data
1667gets read in to \f(CW$in_ref\fR.
1668.Sp
1669\&\f(CW\*(C`input_avail\*(C'\fR is usually used as part of a return expression:
1670.Sp
1671.Vb 4
1672\& return input_avail && do {
1673\& ## process the input just gotten
1674\& 1;
1675\& };
1676.Ve
1677.Sp
1678This technique allows input_avail to return the undef or 0 that a
1679filter normally returns when there's no input to process. If a filter
1680stores intermediate values, however, it will need to react to an
1681undef:
1682.Sp
1683.Vb 7
1684\& my $got = input_avail;
1685\& if ( ! defined $got ) {
1686\& ## No more input ever, flush internal buffers to $out_ref
1687\& }
1688\& return $got unless $got;
1689\& ## Got some input, move as much as need be
1690\& return 1 if $added_to_out_ref;
1691.Ve
1692.IP "get_more_input" 4
1693.IX Item "get_more_input"
1694This is used to fetch more input in to the input variable. It returns
1695undef if there will never be any more input, 0 if there is none now,
1696but there might be in the future, and \s-1TRUE\s0 if more input was gotten.
1697.Sp
1698\&\f(CW\*(C`get_more_input\*(C'\fR is usually used as part of a return expression,
1699see \*(L"input_avail\*(R" for more information.
1700.SH "TODO"
1701.IX Header "TODO"
1702These will be addressed as needed and as time allows.
1703.PP
1704Stall timeout.
1705.PP
1706Expose a list of child process objects. When I do this,
1707each child process is likely to be blessed into IPC::Run::Proc.
1708.PP
1709\&\f(CW$kid\fR\->\fIabort()\fR, \f(CW$kid\fR\->\fIkill()\fR, \f(CW$kid\fR\->signal( \f(CW$num_or_name\fR ).
1710.PP
1711Write tests for /(full_)?results?/ subs.
1712.PP
1713Currently, \fIpump()\fR and \fIrun()\fR only work on systems where \fIselect()\fR works on the
1714filehandles returned by \fIpipe()\fR. This does *not* include ActiveState on Win32,
1715although it does work on cygwin under Win32 (thought the tests whine a bit).
1716I'd like to rectify that, suggestions and patches welcome.
1717.PP
1718Likewise \fIstart()\fR only fully works on \fIfork()\fR/\fIexec()\fR machines (well, just
1719\&\fIfork()\fR if you only ever pass perl subs as subprocesses). There's
1720some scaffolding for calling \fIOpen3::spawn_with_handles()\fR, but that's
1721untested, and not that useful with limited \fIselect()\fR.
1722.PP
1723Support for \f(CW\*(C`\e@sub_cmd\*(C'\fR as an argument to a command which
1724gets replaced with /dev/fd or the name of a temporary file containing foo's
1725output. This is like <(sub_cmd ...) found in bash and csh (\s-1IIRC\s0).
1726.PP
1727Allow multiple harnesses to be combined as independant sets of processes
1728in to one 'meta\-harness'.
1729.PP
1730Allow a harness to be passed in place of an \e@cmd. This would allow
1731multiple harnesses to be aggregated.
1732.PP
1733Ability to add external file descriptors w/ filter chains and endpoints.
1734.PP
1735Ability to add timeouts and timing generators (i.e. repeating timeouts).
1736.PP
1737High resolution timeouts.
1738.SH "Win32 LIMITATIONS"
1739.IX Header "Win32 LIMITATIONS"
1740.IP "Fails on Win9X" 4
1741.IX Item "Fails on Win9X"
1742If you want Win9X support, you'll have to debug it or fund me because I
1743don't use that system any more. The Win32 subsysem has been extended to
1744use temporary files in simple \fIrun()\fR invocations and these may actually
1745work on Win9X too, but I don't have time to work on it.
1746.IP "May deadlock on Win2K (but not WinNT4 or WinXPPro)" 4
1747.IX Item "May deadlock on Win2K (but not WinNT4 or WinXPPro)"
1748Spawning more than one subprocess on Win2K causes a deadlock I haven't
1749figured out yet, but simple uses of \fIrun()\fR often work. Passes all tests
1750on WinXPPro and WinNT.
1751.IP "no support yet for <pty< and >pty>" 4
1752.IX Item "no support yet for <pty< and >pty>"
1753These are likely to be implemented as \*(L"<\*(R" and \*(L">\*(R" with binmode on, not
1754sure.
1755.IP "no support for file descriptors higher than 2 (stderr)" 4
1756.IX Item "no support for file descriptors higher than 2 (stderr)"
1757Win32 only allows passing explicit fds 0, 1, and 2. If you really, really need to pass file handles, us Win32API:: \fIGetOsFHandle()\fR or ::\fIFdGetOsFHandle()\fR to
1758get the integer handle and pass it to the child process using the command
1759line, environment, stdin, intermediary file, or other \s-1IPC\s0 mechnism. Then
1760use that handle in the child (Win32API.pm provides ways to reconstitute
1761Perl file handles from Win32 file handles).
1762.IP "no support for subroutine subprocesses (\s-1CODE\s0 refs)" 4
1763.IX Item "no support for subroutine subprocesses (CODE refs)"
1764Can't \fIfork()\fR, so the subroutines would have no context, and closures certainly
1765have no meaning
1766.Sp
1767Perhaps with Win32 \fIfork()\fR emulation, this can be supported in a limited
1768fashion, but there are other very serious problems with that: all parent
1769fds get \fIdup()\fRed in to the thread emulating the forked process, and that
1770keeps the parent from being able to close all of the appropriate fds.
1771.IP "no support for init => sub {} routines." 4
1772.IX Item "no support for init => sub {} routines."
1773Win32 processes are created from scratch, there is no way to do an init
1774routine that will affect the running child. Some limited support might
1775be implemented one day, do \fIchdir()\fR and \f(CW%ENV\fR changes can be made.
1776.IP "signals" 4
1777.IX Item "signals"
1778Win32 does not fully support signals. \fIsignal()\fR is likely to cause errors
1779unless sending a signal that Perl emulates, and \f(CW\*(C`kill_kill()\*(C'\fR is immediately
1780fatal (there is no grace period).
1781.IP "helper processes" 4
1782.IX Item "helper processes"
1783IPC::Run uses helper processes, one per redirected file, to adapt between the
1784anonymous pipe connected to the child and the \s-1TCP\s0 socket connected to the
1785parent. This is a waste of resources and will change in the future to either
1786use threads (instead of helper processes) or a WaitForMultipleObjects call
1787(instead of select). Please contact me if you can help with the
1788\&\fIWaitForMultipleObjects()\fR approach; I haven't figured out how to get at it
1789without C code.
1790.IP "shutdown pause" 4
1791.IX Item "shutdown pause"
1792There seems to be a pause of up to 1 second between when a child program exits
1793and the corresponding sockets indicate that they are closed in the parent.
1794Not sure why.
1795.IP "binmode" 4
1796.IX Item "binmode"
1797binmode is not supported yet. The underpinnings are implemented, just ask
1798if you need it.
1799.IP "IPC::Run::IO" 4
1800.IX Item "IPC::Run::IO"
1801IPC::Run::IO objects can be used on Unix to read or write arbitrary files. On
1802Win32, they will need to use the same helper processes to adapt from
1803non\-\fIselect()\fRable filehandles to \fIselect()\fRable ones (or perhaps
1804\&\fIWaitForMultipleObjects()\fR will work with them, not sure).
1805.IP "startup race conditions" 4
1806.IX Item "startup race conditions"
1807There seems to be an occasional race condition between child process startup
1808and pipe closings. It seems like if the child is not fully created by the time
1809CreateProcess returns and we close the \s-1TCP\s0 socket being handed to it, the
1810parent socket can also get closed. This is seen with the Win32 pumper
1811applications, not the \*(L"real\*(R" child process being spawned.
1812.Sp
1813I assume this is because the kernel hasn't gotten around to incrementing the
1814reference count on the child's end (since the child was slow in starting), so
1815the parent's closing of the child end causes the socket to be closed, thus
1816closing the parent socket.
1817.Sp
1818Being a race condition, it's hard to reproduce, but I encountered it while
1819testing this code on a drive share to a samba box. In this case, it takes
1820t/run.t a long time to spawn it's chile processes (the parent hangs in the
1821first select for several seconds until the child emits any debugging output).
1822.Sp
1823I have not seen it on local drives, and can't reproduce it at will,
1824unfortunately. The symptom is a \*(L"bad file descriptor in \fIselect()\fR\*(R" error, and,
1825by turning on debugging, it's possible to see that \fIselect()\fR is being called on
1826a no longer open file descriptor that was returned from the \fI_socket()\fR routine
1827in Win32Helper. There's a new \fIconfess()\fR that checks for this (\*(L"\s-1PARENT_HANDLE\s0
1828no longer open\*(R"), but I haven't been able to reproduce it (typically).
1829.SH "LIMITATIONS"
1830.IX Header "LIMITATIONS"
1831On Unix, requires a system that supports \f(CW\*(C`waitpid( $pid, WNOHANG )\*(C'\fR so
1832it can tell if a child process is still running.
1833.PP
1834PTYs don't seem to be non-blocking on some versions of Solaris. Here's a
1835test script contributed by Borislav Deianov <borislav@ensim.com> to see
1836if you have the problem. If it dies, you have the problem.
1837.PP
1838.Vb 1
1839\& #!/usr/bin/perl
1840\&
1841\& use IPC::Run qw(run);
1842\& use Fcntl;
1843\& use IO::Pty;
1844\&
1845\& sub makecmd {
1846\& return [\*(Aqperl\*(Aq, \*(Aq\-e\*(Aq,
1847\& \*(Aq<STDIN>, print "\en" x \*(Aq.$_[0].\*(Aq; while(<STDIN>){last if /end/}\*(Aq];
1848\& }
1849\&
1850\& #pipe R, W;
1851\& #fcntl(W, F_SETFL, O_NONBLOCK);
1852\& #while (syswrite(W, "\en", 1)) { $pipebuf++ };
1853\& #print "pipe buffer size is $pipebuf\en";
1854\& my $pipebuf=4096;
1855\& my $in = "\en" x ($pipebuf * 2) . "end\en";
1856\& my $out;
1857\&
1858\& $SIG{ALRM} = sub { die "Never completed!\en" };
1859\&
1860\& print "reading from scalar via pipe...";
1861\& alarm( 2 );
1862\& run(makecmd($pipebuf * 2), \*(Aq<\*(Aq, \e$in, \*(Aq>\*(Aq, \e$out);
1863\& alarm( 0 );
1864\& print "done\en";
1865\&
1866\& print "reading from code via pipe... ";
1867\& alarm( 2 );
1868\& run(makecmd($pipebuf * 3), \*(Aq<\*(Aq, sub { $t = $in; undef $in; $t}, \*(Aq>\*(Aq, \e$out);
1869\& alarm( 0 );
1870\& print "done\en";
1871\&
1872\& $pty = IO::Pty\->new();
1873\& $pty\->blocking(0);
1874\& $slave = $pty\->slave();
1875\& while ($pty\->syswrite("\en", 1)) { $ptybuf++ };
1876\& print "pty buffer size is $ptybuf\en";
1877\& $in = "\en" x ($ptybuf * 3) . "end\en";
1878\&
1879\& print "reading via pty... ";
1880\& alarm( 2 );
1881\& run(makecmd($ptybuf * 3), \*(Aq<pty<\*(Aq, \e$in, \*(Aq>\*(Aq, \e$out);
1882\& alarm(0);
1883\& print "done\en";
1884.Ve
1885.PP
1886No support for ';', '&&', '||', '{ ... }', etc: use perl's, since \fIrun()\fR
1887returns \s-1TRUE\s0 when the command exits with a 0 result code.
1888.PP
1889Does not provide shell-like string interpolation.
1890.PP
1891No support for \f(CW\*(C`cd\*(C'\fR, \f(CW\*(C`setenv\*(C'\fR, or \f(CW\*(C`export\*(C'\fR: do these in an \fIinit()\fR sub
1892.PP
1893.Vb 8
1894\& run(
1895\& \ecmd,
1896\& ...
1897\& init => sub {
1898\& chdir $dir or die $!;
1899\& $ENV{FOO}=\*(AqBAR\*(Aq
1900\& }
1901\& );
1902.Ve
1903.PP
1904Timeout calculation does not allow absolute times, or specification of
1905days, months, etc.
1906.PP
1907\&\fB\s-1WARNING:\s0\fR Function coprocesses (\f(CW\*(C`run \e&foo, ...\*(C'\fR) suffer from two
1908limitations. The first is that it is difficult to close all filehandles the
1909child inherits from the parent, since there is no way to scan all open
1910FILEHANDLEs in Perl and it both painful and a bit dangerous to close all open
1911file descriptors with \f(CW\*(C`POSIX::close()\*(C'\fR. Painful because we can't tell which
1912fds are open at the \s-1POSIX\s0 level, either, so we'd have to scan all possible fds
1913and close any that we don't want open (normally \f(CW\*(C`exec()\*(C'\fR closes any
1914non-inheritable but we don't \f(CW\*(C`exec()\*(C'\fR for &sub processes.
1915.PP
1916The second problem is that Perl's \s-1DESTROY\s0 subs and other on-exit cleanup gets
1917run in the child process. If objects are instantiated in the parent before the
1918child is forked, the the \s-1DESTROY\s0 will get run once in the parent and once in
1919the child. When coprocess subs exit, POSIX::exit is called to work around this,
1920but it means that objects that are still referred to at that time are not
1921cleaned up. So setting package vars or closure vars to point to objects that
1922rely on \s-1DESTROY\s0 to affect things outside the process (files, etc), will
1923lead to bugs.
1924.PP
1925I goofed on the syntax: \*(L"<pipe\*(R" vs. \*(L"<pty<\*(R" and \*(L">filename\*(R" are both
1926oddities.
1927.SH "TODO"
1928.IX Header "TODO"
1929.ie n .IP "Allow one harness to ""adopt"" another:" 4
1930.el .IP "Allow one harness to ``adopt'' another:" 4
1931.IX Item "Allow one harness to adopt another:"
1932.Vb 2
1933\& $new_h = harness \e@cmd2;
1934\& $h\->adopt( $new_h );
1935.Ve
1936.IP "Close all filehandles not explicitly marked to stay open." 4
1937.IX Item "Close all filehandles not explicitly marked to stay open."
1938The problem with this one is that there's no good way to scan all open
1939FILEHANDLEs in Perl, yet you don't want child processes inheriting handles
1940willy-nilly.
1941.SH "INSPIRATION"
1942.IX Header "INSPIRATION"
1943Well, \fIselect()\fR and \fIwaitpid()\fR badly needed wrapping, and \fIopen3()\fR isn't
1944open-minded enough for me.
1945.PP
1946The shell-like \s-1API\s0 inspired by a message Russ Allbery sent to perl5\-porters,
1947which included:
1948.PP
1949.Vb 4
1950\& I\*(Aqve thought for some time that it would be
1951\& nice to have a module that could handle full Bourne shell pipe syntax
1952\& internally, with fork and exec, without ever invoking a shell. Something
1953\& that you could give things like:
1954\&
1955\& pipeopen (PIPE, [ qw/cat file/ ], \*(Aq|\*(Aq, [ \*(Aqanalyze\*(Aq, @args ], \*(Aq>&3\*(Aq);
1956.Ve
1957.PP
1958Message ylln51p2b6.fsf@windlord.stanford.edu, on 2000/02/04.
1959.SH "SUPPORT"
1960.IX Header "SUPPORT"
1961Bugs should always be submitted via the \s-1CPAN\s0 bug tracker
1962.PP
1963<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=IPC\-Run>
1964.PP
1965For other issues, contact the maintainer (the first listed author)
1966.SH "AUTHORS"
1967.IX Header "AUTHORS"
1968Adam Kennedy <adamk@cpan.org>
1969.PP
1970Barrie Slaymaker <barries@slaysys.com>
1971.SH "COPYRIGHT"
1972.IX Header "COPYRIGHT"
1973Some parts copyright 2008 \- 2009 Adam Kennedy.
1974.PP
1975Copyright 1999 Barrie Slaymaker.
1976.PP
1977You may distribute under the terms of either the \s-1GNU\s0 General Public
1978License or the Artistic License, as specified in the \s-1README\s0 file.