Server IP : 103.119.228.120 / Your IP : 18.119.124.52 Web Server : Apache System : Linux v8.techscape8.com 3.10.0-1160.119.1.el7.tuxcare.els2.x86_64 #1 SMP Mon Jul 15 12:09:18 UTC 2024 x86_64 User : nobody ( 99) PHP Version : 5.6.40 Disable Function : shell_exec,symlink,system,exec,proc_get_status,proc_nice,proc_terminate,define_syslog_variables,syslog,openlog,closelog,escapeshellcmd,passthru,ocinum cols,ini_alter,leak,listen,chgrp,apache_note,apache_setenv,debugger_on,debugger_off,ftp_exec,dl,dll,myshellexec,proc_open,socket_bind,proc_close,escapeshellarg,parse_ini_filepopen,fpassthru,exec,passthru,escapeshellarg,escapeshellcmd,proc_close,proc_open,ini_alter,popen,show_source,proc_nice,proc_terminate,proc_get_status,proc_close,pfsockopen,leak,apache_child_terminate,posix_kill,posix_mkfifo,posix_setpgid,posix_setsid,posix_setuid,dl,symlink,shell_exec,system,dl,passthru,escapeshellarg,escapeshellcmd,myshellexec,c99_buff_prepare,c99_sess_put,fpassthru,getdisfunc,fx29exec,fx29exec2,is_windows,disp_freespace,fx29sh_getupdate,fx29_buff_prepare,fx29_sess_put,fx29shexit,fx29fsearch,fx29ftpbrutecheck,fx29sh_tools,fx29sh_about,milw0rm,imagez,sh_name,myshellexec,checkproxyhost,dosyayicek,c99_buff_prepare,c99_sess_put,c99getsource,c99sh_getupdate,c99fsearch,c99shexit,view_perms,posix_getpwuid,posix_getgrgid,posix_kill,parse_perms,parsesort,view_perms_color,set_encoder_input,ls_setcheckboxall,ls_reverse_all,rsg_read,rsg_glob,selfURL,dispsecinfo,unix2DosTime,addFile,system,get_users,view_size,DirFiles,DirFilesWide,DirPrintHTMLHeaders,GetFilesTotal,GetTitles,GetTimeTotal,GetMatchesCount,GetFileMatchesCount,GetResultFiles,fs_copy_dir,fs_copy_obj,fs_move_dir,fs_move_obj,fs_rmdir,SearchText,getmicrotime MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /usr/local/share/man/man3/ |
Upload File : |
.\" Automatically generated by Pod::Man 2.27 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "IPC::Run 3" .TH IPC::Run 3 "2014-12-14" "perl v5.16.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" IPC::Run \- system() and background procs w/ piping, redirs, ptys (Unix, Win32) .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& ## First,a command to run: \& my @cat = qw( cat ); \& \& ## Using run() instead of system(): \& use IPC::Run qw( run timeout ); \& \& run \e@cmd, \e$in, \e$out, \e$err, timeout( 10 ) or die "cat: $?" \& \& # Can do I/O to sub refs and filenames, too: \& run \e@cmd, \*(Aq<\*(Aq, "in.txt", \e&out, \e&err or die "cat: $?" \& run \e@cat, \*(Aq<\*(Aq, "in.txt", \*(Aq>>\*(Aq, "out.txt", \*(Aq2>>\*(Aq, "err.txt"; \& \& \& # Redirecting using psuedo\-terminals instad of pipes. \& run \e@cat, \*(Aq<pty<\*(Aq, \e$in, \*(Aq>pty>\*(Aq, \e$out_and_err; \& \& ## Scripting subprocesses (like Expect): \& \& use IPC::Run qw( start pump finish timeout ); \& \& # Incrementally read from / write to scalars. \& # $in is drained as it is fed to cat\*(Aqs stdin, \& # $out accumulates cat\*(Aqs stdout \& # $err accumulates cat\*(Aqs stderr \& # $h is for "harness". \& my $h = start \e@cat, \e$in, \e$out, \e$err, timeout( 10 ); \& \& $in .= "some input\en"; \& pump $h until $out =~ /input\en/g; \& \& $in .= "some more input\en"; \& pump $h until $out =~ /\eG.*more input\en/; \& \& $in .= "some final input\en"; \& finish $h or die "cat returned $?"; \& \& warn $err if $err; \& print $out; ## All of cat\*(Aqs output \& \& # Piping between children \& run \e@cat, \*(Aq|\*(Aq, \e@gzip; \& \& # Multiple children simultaneously (run() blocks until all \& # children exit, use start() for background execution): \& run \e@foo1, \*(Aq&\*(Aq, \e@foo2; \& \& # Calling \e&set_up_child in the child before it executes the \& # command (only works on systems with true fork() & exec()) \& # exceptions thrown in set_up_child() will be propagated back \& # to the parent and thrown from run(). \& run \e@cat, \e$in, \e$out, \& init => \e&set_up_child; \& \& # Read from / write to file handles you open and close \& open IN, \*(Aq<in.txt\*(Aq or die $!; \& open OUT, \*(Aq>out.txt\*(Aq or die $!; \& print OUT "preamble\en"; \& run \e@cat, \e*IN, \e*OUT or die "cat returned $?"; \& print OUT "postamble\en"; \& close IN; \& close OUT; \& \& # Create pipes for you to read / write (like IPC::Open2 & 3). \& $h = start \& \e@cat, \& \*(Aq<pipe\*(Aq, \e*IN, \& \*(Aq>pipe\*(Aq, \e*OUT, \& \*(Aq2>pipe\*(Aq, \e*ERR \& or die "cat returned $?"; \& print IN "some input\en"; \& close IN; \& print <OUT>, <ERR>; \& finish $h; \& \& # Mixing input and output modes \& run \e@cat, \*(Aqin.txt\*(Aq, \e&catch_some_out, \e*ERR_LOG ); \& \& # Other redirection constructs \& run \e@cat, \*(Aq>&\*(Aq, \e$out_and_err; \& run \e@cat, \*(Aq2>&1\*(Aq; \& run \e@cat, \*(Aq0<&3\*(Aq; \& run \e@cat, \*(Aq<&\-\*(Aq; \& run \e@cat, \*(Aq3<\*(Aq, \e$in3; \& run \e@cat, \*(Aq4>\*(Aq, \e$out4; \& # etc. \& \& # Passing options: \& run \e@cat, \*(Aqin.txt\*(Aq, debug => 1; \& \& # Call this system\*(Aqs shell, returns TRUE on 0 exit code \& # THIS IS THE OPPOSITE SENSE OF system()\*(Aqs RETURN VALUE \& run "cat a b c" or die "cat returned $?"; \& \& # Launch a sub process directly, no shell. Can\*(Aqt do redirection \& # with this form, it\*(Aqs here to behave like system() with an \& # inverted result. \& $r = run "cat a b c"; \& \& # Read from a file in to a scalar \& run io( "filename", \*(Aqr\*(Aq, \e$recv ); \& run io( \e*HANDLE, \*(Aqr\*(Aq, \e$recv ); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" IPC::Run allows you to run and interact with child processes using files, pipes, and pseudo-ttys. Both \fIsystem()\fR\-style and scripted usages are supported and may be mixed. Likewise, functional and \s-1OO API\s0 styles are both supported and may be mixed. .PP Various redirection operators reminiscent of those seen on common Unix and \s-1DOS\s0 command lines are provided. .PP Before digging in to the details a few \s-1LIMITATIONS\s0 are important enough to be mentioned right up front: .IP "Win32 Support" 4 .IX Item "Win32 Support" Win32 support is working but \fB\s-1EXPERIMENTAL\s0\fR, but does pass all relevant tests on \s-1NT 4.0. \s0 See \*(L"Win32 \s-1LIMITATIONS\*(R"\s0. .IP "pty Support" 4 .IX Item "pty Support" If you need pty support, IPC::Run should work well enough most of the time, but IO::Pty is being improved, and IPC::Run will be improved to use IO::Pty's new features when it is release. .Sp The basic problem is that the pty needs to initialize itself before the parent writes to the master pty, or the data written gets lost. So IPC::Run does a \fIsleep\fR\|(1) in the parent after forking to (hopefully) give the child a chance to run. This is a kludge that works well on non heavily loaded systems :(. .Sp ptys are not supported yet under Win32, but will be emulated... .IP "Debugging Tip" 4 .IX Item "Debugging Tip" You may use the environment variable \f(CW\*(C`IPCRUNDEBUG\*(C'\fR to see what's going on under the hood: .Sp .Vb 5 \& $ IPCRUNDEBUG=basic myscript # prints minimal debugging \& $ IPCRUNDEBUG=data myscript # prints all data reads/writes \& $ IPCRUNDEBUG=details myscript # prints lots of low\-level details \& $ IPCRUNDEBUG=gory myscript # (Win32 only) prints data moving through \& # the helper processes. .Ve .PP We now return you to your regularly scheduled documentation. .SS "Harnesses" .IX Subsection "Harnesses" Child processes and I/O handles are gathered in to a harness, then started and run until the processing is finished or aborted. .SS "\fIrun()\fP vs. \fIstart()\fP; \fIpump()\fP; \fIfinish()\fP;" .IX Subsection "run() vs. start(); pump(); finish();" There are two modes you can run harnesses in: \fIrun()\fR functions as an enhanced \fIsystem()\fR, and \fIstart()\fR/\fIpump()\fR/\fIfinish()\fR allow for background processes and scripted interactions with them. .PP When using \fIrun()\fR, all data to be sent to the harness is set up in advance (though one can feed subprocesses input from subroutine refs to get around this limitation). The harness is run and all output is collected from it, then any child processes are waited for: .PP .Vb 3 \& run \e@cmd, \e<<IN, \e$out; \& blah \& IN \& \& ## To precompile harnesses and run them later: \& my $h = harness \e@cmd, \e<<IN, \e$out; \& blah \& IN \& \& run $h; .Ve .PP The background and scripting \s-1API\s0 is provided by \fIstart()\fR, \fIpump()\fR, and \&\fIfinish()\fR: \fIstart()\fR creates a harness if need be (by calling \fIharness()\fR) and launches any subprocesses, \fIpump()\fR allows you to poll them for activity, and \fIfinish()\fR then monitors the harnessed activities until they complete. .PP .Vb 3 \& ## Build the harness, open all pipes, and launch the subprocesses \& my $h = start \e@cat, \e$in, \e$out; \& $in = "first input\en"; \& \& ## Now do I/O. start() does no I/O. \& pump $h while length $in; ## Wait for all input to go \& \& ## Now do some more I/O. \& $in = "second input\en"; \& pump $h until $out =~ /second input/; \& \& ## Clean up \& finish $h or die "cat returned $?"; .Ve .PP You can optionally compile the harness with \fIharness()\fR prior to \&\fIstart()\fRing or \fIrun()\fRing, and you may omit \fIstart()\fR between \fIharness()\fR and \&\fIpump()\fR. You might want to do these things if you compile your harnesses ahead of time. .SS "Using regexps to match output" .IX Subsection "Using regexps to match output" As shown in most of the scripting examples, the read-to-scalar facility for gathering subcommand's output is often used with regular expressions to detect stopping points. This is because subcommand output often arrives in dribbles and drabs, often only a character or line at a time. This output is input for the main program and piles up in variables like the \f(CW$out\fR and \f(CW$err\fR in our examples. .PP Regular expressions can be used to wait for appropriate output in several ways. The \f(CW\*(C`cat\*(C'\fR example in the previous section demonstrates how to \fIpump()\fR until some string appears in the output. Here's an example that uses \f(CW\*(C`smb\*(C'\fR to fetch files from a remote server: .PP .Vb 1 \& $h = harness \e@smbclient, \e$in, \e$out; \& \& $in = "cd /src\en"; \& $h\->pump until $out =~ /^smb.*> \eZ/m; \& die "error cding to /src:\en$out" if $out =~ "ERR"; \& $out = \*(Aq\*(Aq; \& \& $in = "mget *\en"; \& $h\->pump until $out =~ /^smb.*> \eZ/m; \& die "error retrieving files:\en$out" if $out =~ "ERR"; \& \& $in = "quit\en"; \& $h\->finish; .Ve .PP Notice that we carefully clear \f(CW$out\fR after the first command/response cycle? That's because IPC::Run does not delete \f(CW$out\fR when we continue, and we don't want to trip over the old output in the second command/response cycle. .PP Say you want to accumulate all the output in \f(CW$out\fR and analyze it afterwards. Perl offers incremental regular expression matching using the \f(CW\*(C`m//gc\*(C'\fR and pattern matching idiom and the \f(CW\*(C`\eG\*(C'\fR assertion. IPC::Run is careful not to disturb the current \f(CW\*(C`pos()\*(C'\fR value for scalars it appends data to, so we could modify the above so as not to destroy \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 from tripping over the previous prompt and the \f(CW\*(C`/c\*(C'\fR keeps us from resetting the prior match position if the expected prompt doesn't materialize immediately: .PP .Vb 1 \& $h = harness \e@smbclient, \e$in, \e$out; \& \& $in = "cd /src\en"; \& $h\->pump until $out =~ /^smb.*> \eZ/mgc; \& die "error cding to /src:\en$out" if $out =~ "ERR"; \& \& $in = "mget *\en"; \& $h\->pump until $out =~ /^smb.*> \eZ/mgc; \& die "error retrieving files:\en$out" if $out =~ "ERR"; \& \& $in = "quit\en"; \& $h\->finish; \& \& analyze( $out ); .Ve .PP When using this technique, you may want to preallocate \f(CW$out\fR to have plenty of memory or you may find that the act of growing \f(CW$out\fR each time new input arrives causes an \f(CW\*(C`O(length($out)^2)\*(C'\fR slowdown as \f(CW$out\fR grows. Say we expect no more than 10,000 characters of input at the most. To preallocate memory to \f(CW$out\fR, do something like: .PP .Vb 2 \& my $out = "x" x 10_000; \& $out = ""; .Ve .PP \&\f(CW\*(C`perl\*(C'\fR will allocate at least 10,000 characters' worth of space, then mark the \f(CW$out\fR as having 0 length without freeing all that yummy \s-1RAM.\s0 .SS "Timeouts and Timers" .IX Subsection "Timeouts and Timers" More than likely, you don't want your subprocesses to run forever, and sometimes it's nice to know that they're going a little slowly. Timeouts throw exceptions after a some time has elapsed, timers merely cause \fIpump()\fR to return after some time has elapsed. Neither is reset/restarted automatically. .PP Timeout objects are created by calling timeout( \f(CW$interval\fR ) and passing the result to \fIrun()\fR, \fIstart()\fR or \fIharness()\fR. The timeout period starts ticking just after all the child processes have been \fIfork()\fRed or \&\fIspawn()\fRed, and are polled for expiration in \fIrun()\fR, \fIpump()\fR and \fIfinish()\fR. If/when they expire, an exception is thrown. This is typically useful to keep a subprocess from taking too long. .PP If a timeout occurs in \fIrun()\fR, all child processes will be terminated and all file/pipe/ptty descriptors opened by \fIrun()\fR will be closed. File descriptors opened by the parent process and passed in to \fIrun()\fR are not closed in this event. .PP If a timeout occurs in \fIpump()\fR, \fIpump_nb()\fR, or \fIfinish()\fR, it's up to you to decide whether to \fIkill_kill()\fR all the children or to implement some more graceful fallback. No I/O will be closed in \fIpump()\fR, \fIpump_nb()\fR or \&\fIfinish()\fR by such an exception (though I/O is often closed down in those routines during the natural course of events). .PP Often an exception is too harsh. timer( \f(CW$interval\fR ) creates timer objects that merely prevent \fIpump()\fR from blocking forever. This can be useful for detecting stalled I/O or printing a soothing message or \*(L".\*(R" to pacify an anxious user. .PP Timeouts and timers can both be restarted at any time using the timer's \&\fIstart()\fR method (this is not the \fIstart()\fR that launches subprocesses). To restart a timer, you need to keep a reference to the timer: .PP .Vb 2 \& ## Start with a nice long timeout to let smbclient connect. If \& ## pump or finish take too long, an exception will be thrown. \& \& my $h; \& eval { \& $h = harness \e@smbclient, \e$in, \e$out, \e$err, ( my $t = timeout 30 ); \& sleep 11; # No effect: timer not running yet \& \& start $h; \& $in = "cd /src\en"; \& pump $h until ! length $in; \& \& $in = "ls\en"; \& ## Now use a short timeout, since this should be faster \& $t\->start( 5 ); \& pump $h until ! length $in; \& \& $t\->start( 10 ); ## Give smbclient a little while to shut down. \& $h\->finish; \& }; \& if ( $@ ) { \& my $x = $@; ## Preserve $@ in case another exception occurs \& $h\->kill_kill; ## kill it gently, then brutally if need be, or just \& ## brutally on Win32. \& die $x; \& } .Ve .PP Timeouts and timers are \fInot\fR checked once the subprocesses are shut down; they will not expire in the interval between the last valid process and when IPC::Run scoops up the processes' result codes, for instance. .SS "Spawning synchronization, child exception propagation" .IX Subsection "Spawning synchronization, child exception propagation" \&\fIstart()\fR pauses the parent until the child executes the command or \s-1CODE\s0 reference and propagates any exceptions thrown (including \fIexec()\fR failure) back to the parent. This has several pleasant effects: any exceptions thrown in the child, including \fIexec()\fR failure, come flying out of \fIstart()\fR or \fIrun()\fR as though they had occurred in the parent. .PP This includes exceptions your code thrown from init subs. In this example: .PP .Vb 4 \& eval { \& run \e@cmd, init => sub { die "blast it! foiled again!" }; \& }; \& print $@; .Ve .PP the exception \*(L"blast it! foiled again\*(R" will be thrown from the child process (preventing the \fIexec()\fR) and printed by the parent. .PP In situations like .PP .Vb 1 \& run \e@cmd1, "|", \e@cmd2, "|", \e@cmd3; .Ve .PP \&\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. This can save time and prevent oddball errors emitted by later commands when earlier commands fail to execute. Note that IPC::Run doesn't start any commands unless it can find the executables referenced by all commands. These executables must pass both the \f(CW\*(C`\-f\*(C'\fR and \f(CW\*(C`\-x\*(C'\fR tests described in perlfunc. .PP Another nice effect is that \fIinit()\fR subs can take their time doing things and there will be no problems caused by a parent continuing to execute before a child's \fIinit()\fR routine is complete. Say the \fIinit()\fR routine needs to open a socket or a temp file that the parent wants to connect to; without this synchronization, the parent will need to implement a retry loop to wait for the child to run, since often, the parent gets a lot of things done before the child's first timeslice is allocated. .PP This is also quite necessary for pseudo-tty initialization, which needs to take place before the parent writes to the child via pty. Writes that occur before the pty is set up can get lost. .PP A final, minor, nicety is that debugging output from the child will be emitted before the parent continues on, making for much clearer debugging output in complex situations. .PP The only drawback I can conceive of is that the parent can't continue to operate while the child is being initted. If this ever becomes a problem in the field, we can implement an option to avoid this behavior, but I don't expect it to. .PP \&\fBWin32\fR: executing \s-1CODE\s0 references isn't supported on Win32, see \&\*(L"Win32 \s-1LIMITATIONS\*(R"\s0 for details. .SS "Syntax" .IX Subsection "Syntax" \&\fIrun()\fR, \fIstart()\fR, and \fIharness()\fR can all take a harness specification as input. A harness specification is either a single string to be passed to the systems' shell: .PP .Vb 1 \& run "echo \*(Aqhi there\*(Aq"; .Ve .PP or a list of commands, io operations, and/or timers/timeouts to execute. Consecutive commands must be separated by a pipe operator '|' or an '&'. External commands are passed in as array references, and, on systems supporting \fIfork()\fR, Perl code may be passed in as subs: .PP .Vb 6 \& run \e@cmd; \& run \e@cmd1, \*(Aq|\*(Aq, \e@cmd2; \& run \e@cmd1, \*(Aq&\*(Aq, \e@cmd2; \& run \e&sub1; \& run \e&sub1, \*(Aq|\*(Aq, \e&sub2; \& run \e&sub1, \*(Aq&\*(Aq, \e&sub2; .Ve .PP \&'|' pipes the stdout of \e@cmd1 the stdin of \e@cmd2, just like a shell pipe. '&' does not. Child processes to the right of a '&' will have their stdin closed unless it's redirected-to. .PP IPC::Run::IO objects may be passed in as well, whether or not child processes are also specified: .PP .Vb 1 \& run io( "infile", ">", \e$in ), io( "outfile", "<", \e$in ); .Ve .PP as can IPC::Run::Timer objects: .PP .Vb 1 \& run \e@cmd, io( "outfile", "<", \e$in ), timeout( 10 ); .Ve .PP Commands may be followed by scalar, sub, or i/o handle references for redirecting child process input & output: .PP .Vb 4 \& run \e@cmd, \eundef, \e$out; \& run \e@cmd, \e$in, \e$out; \& run \e@cmd1, \e&in, \*(Aq|\*(Aq, \e@cmd2, \e*OUT; \& run \e@cmd1, \e*IN, \*(Aq|\*(Aq, \e@cmd2, \e&out; .Ve .PP This is known as succinct redirection syntax, since \fIrun()\fR, \fIstart()\fR and \fIharness()\fR, figure out which file descriptor to redirect and how. File descriptor 0 is presumed to be an input for the child process, all others are outputs. The assumed file descriptor always starts at 0, unless the command is being piped to, in which case it starts at 1. .PP To be explicit about your redirects, or if you need to do more complex things, there's also a redirection operator syntax: .PP .Vb 8 \& run \e@cmd, \*(Aq<\*(Aq, \eundef, \*(Aq>\*(Aq, \e$out; \& run \e@cmd, \*(Aq<\*(Aq, \eundef, \*(Aq>&\*(Aq, \e$out_and_err; \& run( \& \e@cmd1, \& \*(Aq<\*(Aq, \e$in, \& \*(Aq|\*(Aq, \e@cmd2, \& \e$out \& ); .Ve .PP Operator syntax is required if you need to do something other than simple redirection to/from scalars or subs, like duping or closing file descriptors or redirecting to/from a named file. The operators are covered in detail below. .PP After each \e@cmd (or \e&foo), parsing begins in succinct mode and toggles to operator syntax mode when an operator (ie plain scalar, not a ref) is seen. Once in operator syntax mode, parsing only reverts to succinct mode when a '|' or \&'&' is seen. .PP In succinct mode, each parameter after the \e@cmd specifies what to do with the next highest file descriptor. These File descriptor start with 0 (stdin) unless stdin is being piped to (\f(CW\*(C`\*(Aq|\*(Aq, \e@cmd\*(C'\fR), in which case they start with 1 (stdout). Currently, being on the left of a pipe (\f(CW\*(C`\e@cmd, \e$out, \e$err, \*(Aq|\*(Aq\*(C'\fR) does \fInot\fR cause stdout to be skipped, though this may change since it's not as DWIMerly as it could be. Only stdin is assumed to be an input in succinct mode, all others are assumed to be outputs. .PP If no piping or redirection is specified for a child, it will inherit the parent's open file handles as dictated by your system's close-on-exec behavior and the $^F flag, except that processes after a \&'&' will not inherit the parent's stdin. Also note that $^F does not affect file descriptors obtained via \s-1POSIX,\s0 since it only applies to full-fledged Perl file handles. Such processes will have their stdin closed unless it has been redirected-to. .PP If you want to close a child processes stdin, you may do any of: .PP .Vb 4 \& run \e@cmd, \eundef; \& run \e@cmd, \e""; \& run \e@cmd, \*(Aq<&\-\*(Aq; \& run \e@cmd, \*(Aq0<&\-\*(Aq; .Ve .PP Redirection is done by placing redirection specifications immediately after a command or child subroutine: .PP .Vb 2 \& run \e@cmd1, \e$in, \*(Aq|\*(Aq, \e@cmd2, \e$out; \& run \e@cmd1, \*(Aq<\*(Aq, \e$in, \*(Aq|\*(Aq, \e@cmd2, \*(Aq>\*(Aq, \e$out; .Ve .PP If you omit the redirection operators, descriptors are counted starting at 0. Descriptor 0 is assumed to be input, all others are outputs. A leading '|' consumes descriptor 0, so this works as expected. .PP .Vb 1 \& run \e@cmd1, \e$in, \*(Aq|\*(Aq, \e@cmd2, \e$out; .Ve .PP The parameter following a redirection operator can be a scalar ref, a subroutine ref, a file name, an open filehandle, or a closed filehandle. .PP If it's a scalar ref, the child reads input from or sends output to that variable: .PP .Vb 3 \& $in = "Hello World.\en"; \& run \e@cat, \e$in, \e$out; \& print $out; .Ve .PP Scalars used in incremental (\fIstart()\fR/\fIpump()\fR/\fIfinish()\fR) applications are treated as queues: input is removed from input scalers, resulting in them dwindling to '', and output is appended to output scalars. This is not true of harnesses \fIrun()\fR in batch mode. .PP It's usually wise to append new input to be sent to the child to the input queue, and you'll often want to zap output queues to '' before pumping. .PP .Vb 7 \& $h = start \e@cat, \e$in; \& $in = "line 1\en"; \& pump $h; \& $in .= "line 2\en"; \& pump $h; \& $in .= "line 3\en"; \& finish $h; .Ve .PP The final call to \fIfinish()\fR must be there: it allows the child process(es) to run to completion and waits for their exit values. .SH "OBSTINATE CHILDREN" .IX Header "OBSTINATE CHILDREN" Interactive applications are usually optimized for human use. This can help or hinder trying to interact with them through modules like IPC::Run. Frequently, programs alter their behavior when they detect that stdin, stdout, or stderr are not connected to a tty, assuming that they are being run in batch mode. Whether this helps or hurts depends on which optimizations change. And there's often no way of telling what a program does in these areas other than trial and error and, occasionally, reading the source. This includes different versions and implementations of the same program. .PP All hope is not lost, however. Most programs behave in reasonably tractable manners, once you figure out what it's trying to do. .PP Here are some of the issues you might need to be aware of. .IP "\(bu" 4 \&\fIfflush()\fRing stdout and stderr .Sp This lets the user see stdout and stderr immediately. Many programs undo this optimization if stdout is not a tty, making them harder to manage by things like IPC::Run. .Sp Many programs decline to fflush stdout or stderr if they do not detect a tty there. Some ftp commands do this, for instance. .Sp If this happens to you, look for a way to force interactive behavior, like a command line switch or command. If you can't, you will need to use a pseudo terminal ('<pty<' and '>pty>'). .IP "\(bu" 4 false prompts .Sp Interactive programs generally do not guarantee that output from user commands won't contain a prompt string. For example, your shell prompt might be a '$', and a file named '$' might be the only file in a directory listing. .Sp This can make it hard to guarantee that your output parser won't be fooled into early termination of results. .Sp To help work around this, you can see if the program can alter it's prompt, and use something you feel is never going to occur in actual practice. .Sp You should also look for your prompt to be the only thing on a line: .Sp .Vb 1 \& pump $h until $out =~ /^<SILLYPROMPT>\es?\ez/m; .Ve .Sp (use \f(CW\*(C`(?!\en)\eZ\*(C'\fR in place of \f(CW\*(C`\ez\*(C'\fR on older perls). .Sp You can also take the approach that IPC::ChildSafe takes and emit a command with known output after each 'real' command you issue, then look for this known output. See \fInew_appender()\fR and \fInew_chunker()\fR for filters that can help with this task. .Sp If it's not convenient or possibly to alter a prompt or use a known command/response pair, you might need to autodetect the prompt in case the local version of the child program is different then the one you tested with, or if the user has control over the look & feel of the prompt. .IP "\(bu" 4 Refusing to accept input unless stdin is a tty. .Sp Some programs, for security reasons, will only accept certain types of input from a tty. su, notable, will not prompt for a password unless it's connected to a tty. .Sp If this is your situation, use a pseudo terminal ('<pty<' and '>pty>'). .IP "\(bu" 4 Not prompting unless connected to a tty. .Sp Some programs don't prompt unless stdin or stdout is a tty. See if you can turn prompting back on. If not, see if you can come up with a command that you can issue after every real command and look for it's output, as IPC::ChildSafe does. There are two filters included with IPC::Run that can help with doing this: appender and chunker (see \fInew_appender()\fR and \&\fInew_chunker()\fR). .IP "\(bu" 4 Different output format when not connected to a tty. .Sp Some commands alter their formats to ease machine parsability when they aren't connected to a pipe. This is actually good, but can be surprising. .SH "PSEUDO TERMINALS" .IX Header "PSEUDO TERMINALS" On systems providing pseudo terminals under /dev, IPC::Run can use IO::Pty (available on \s-1CPAN\s0) to provide a terminal environment to subprocesses. This is necessary when the subprocess really wants to think it's connected to a real terminal. .SS "\s-1CAVEATS\s0" .IX Subsection "CAVEATS" Psuedo-terminals are not pipes, though they are similar. Here are some differences to watch out for. .IP "Echoing" 4 .IX Item "Echoing" Sending to stdin will cause an echo on stdout, which occurs before each line is passed to the child program. There is currently no way to disable this, although the child process can and should disable it for things like passwords. .IP "Shutdown" 4 .IX Item "Shutdown" IPC::Run cannot close a pty until all output has been collected. This means that it is not possible to send an \s-1EOF\s0 to stdin by half-closing the pty, as we can when using a pipe to stdin. .Sp This means that you need to send the child process an exit command or signal, or \fIrun()\fR / \fIfinish()\fR will time out. Be careful not to expect a prompt after sending the exit command. .IP "Command line editing" 4 .IX Item "Command line editing" Some subprocesses, notable shells that depend on the user's prompt settings, will reissue the prompt plus the command line input so far once for each character. .IP "'>pty>' means '&>pty>', not '1>pty>'" 4 .IX Item "'>pty>' means '&>pty>', not '1>pty>'" The pseudo terminal redirects both stdout and stderr unless you specify a file descriptor. If you want to grab stderr separately, do this: .Sp .Vb 1 \& start \e@cmd, \*(Aq<pty<\*(Aq, \e$in, \*(Aq>pty>\*(Aq, \e$out, \*(Aq2>\*(Aq, \e$err; .Ve .IP "stdin, stdout, and stderr not inherited" 4 .IX Item "stdin, stdout, and stderr not inherited" Child processes harnessed to a pseudo terminal have their stdin, stdout, and stderr completely closed before any redirection operators take effect. This casts of the bonds of the controlling terminal. This is not done when using pipes. .Sp Right now, this affects all children in a harness that has a pty in use, even if that pty would not affect a particular child. That's a bug and will be fixed. Until it is, it's best not to mix-and-match children. .SS "Redirection Operators" .IX Subsection "Redirection Operators" .Vb 3 \& Operator SHNP Description \& ======== ==== =========== \& <, N< SHN Redirects input to a child\*(Aqs fd N (0 assumed) \& \& >, N> SHN Redirects output from a child\*(Aqs fd N (1 assumed) \& >>, N>> SHN Like \*(Aq>\*(Aq, but appends to scalars or named files \& >&, &> SHN Redirects stdout & stderr from a child process \& \& <pty, N<pty S Like \*(Aq<\*(Aq, but uses a pseudo\-tty instead of a pipe \& >pty, N>pty S Like \*(Aq>\*(Aq, but uses a pseudo\-tty instead of a pipe \& \& N<&M Dups input fd N to input fd M \& M>&N Dups output fd N to input fd M \& N<&\- Closes fd N \& \& <pipe, N<pipe P Pipe opens H for caller to read, write, close. \& >pipe, N>pipe P Pipe opens H for caller to read, write, close. .Ve .PP \&'N' and 'M' are placeholders for integer file descriptor numbers. The terms 'input' and 'output' are from the child process's perspective. .PP The \s-1SHNP\s0 field indicates what parameters an operator can take: .PP .Vb 6 \& S: \e$scalar or \e&function references. Filters may be used with \& these operators (and only these). \& H: \e*HANDLE or IO::Handle for caller to open, and close \& N: "file name". \& P: \e*HANDLE opened by IPC::Run as the parent end of a pipe, but read \& and written to and closed by the caller (like IPC::Open3). .Ve .IP "Redirecting input: [n]<, [n]<pipe" 4 .IX Item "Redirecting input: [n]<, [n]<pipe" You can input the child reads on file descriptor number n to come from a scalar variable, subroutine, file handle, or a named file. If stdin is not redirected, the parent's stdin is inherited. .Sp .Vb 2 \& run \e@cat, \eundef ## Closes child\*(Aqs stdin immediately \& or die "cat returned $?"; \& \& run \e@cat, \e$in; \& \& run \e@cat, \e<<TOHERE; \& blah \& TOHERE \& \& run \e@cat, \e&input; ## Calls &input, feeding data returned \& ## to child\*(Aqs. Closes child\*(Aqs stdin \& ## when undef is returned. .Ve .Sp Redirecting from named files requires you to use the input redirection operator: .Sp .Vb 2 \& run \e@cat, \*(Aq<.profile\*(Aq; \& run \e@cat, \*(Aq<\*(Aq, \*(Aq.profile\*(Aq; \& \& open IN, "<foo"; \& run \e@cat, \e*IN; \& run \e@cat, *IN{IO}; .Ve .Sp The form used second example here is the safest, since filenames like \*(L"0\*(R" and \*(L"&more\en\*(R" won't confuse &run: .Sp You can't do either of .Sp .Vb 2 \& run \e@a, *IN; ## INVALID \& run \e@a, \*(Aq<\*(Aq, *IN; ## BUGGY: Reads file named like "*main::A" .Ve .Sp because perl passes a scalar containing a string that looks like \*(L"*main::A\*(R" to &run, and &run can't tell the difference between that and a redirection operator or a file name. &run guarantees that any scalar you pass after a redirection operator is a file name. .Sp If your child process will take input from file descriptors other than 0 (stdin), you can use a redirection operator with any of the valid input forms (scalar ref, sub ref, etc.): .Sp .Vb 1 \& run \e@cat, \*(Aq3<\*(Aq, \e$in3; .Ve .Sp When redirecting input from a scalar ref, the scalar ref is used as a queue. This allows you to use &harness and \fIpump()\fR to feed incremental bits of input to a coprocess. See \*(L"Coprocesses\*(R" below for more information. .Sp The <pipe operator opens the write half of a pipe on the filehandle glob reference it takes as an argument: .Sp .Vb 5 \& $h = start \e@cat, \*(Aq<pipe\*(Aq, \e*IN; \& print IN "hello world\en"; \& pump $h; \& close IN; \& finish $h; .Ve .Sp Unlike the other '<' operators, IPC::Run does nothing further with it: you are responsible for it. The previous example is functionally equivalent to: .Sp .Vb 6 \& pipe( \e*R, \e*IN ) or die $!; \& $h = start \e@cat, \*(Aq<\*(Aq, \e*IN; \& print IN "hello world\en"; \& pump $h; \& close IN; \& finish $h; .Ve .Sp This is like the behavior of IPC::Open2 and IPC::Open3. .Sp \&\fBWin32\fR: The handle returned is actually a socket handle, so you can use \fIselect()\fR on it. .IP "Redirecting output: [n]>, [n]>>, [n]>&[m], [n]>pipe" 4 .IX Item "Redirecting output: [n]>, [n]>>, [n]>&[m], [n]>pipe" You can redirect any output the child emits to a scalar variable, subroutine, file handle, or file name. You can have &run truncate or append to named files or scalars. If you are redirecting stdin as well, or if the command is on the receiving end of a pipeline ('|'), you can omit the redirection operator: .Sp .Vb 3 \& @ls = ( \*(Aqls\*(Aq ); \& run \e@ls, \eundef, \e$out \& or die "ls returned $?"; \& \& run \e@ls, \eundef, \e&out; ## Calls &out each time some output \& ## is received from the child\*(Aqs \& ## when undef is returned. \& \& run \e@ls, \eundef, \*(Aq2>ls.err\*(Aq; \& run \e@ls, \*(Aq2>\*(Aq, \*(Aqls.err\*(Aq; .Ve .Sp The two parameter form guarantees that the filename will not be interpreted as a redirection operator: .Sp .Vb 2 \& run \e@ls, \*(Aq>\*(Aq, "&more"; \& run \e@ls, \*(Aq2>\*(Aq, ">foo\en"; .Ve .Sp You can pass file handles you've opened for writing: .Sp .Vb 3 \& open( *OUT, ">out.txt" ); \& open( *ERR, ">err.txt" ); \& run \e@cat, \e*OUT, \e*ERR; .Ve .Sp Passing a scalar reference and a code reference requires a little more work, but allows you to capture all of the output in a scalar or each piece of output by a callback: .Sp These two do the same things: .Sp .Vb 1 \& run( [ \*(Aqls\*(Aq ], \*(Aq2>\*(Aq, sub { $err_out .= $_[0] } ); .Ve .Sp does the same basic thing as: .Sp .Vb 1 \& run( [ \*(Aqls\*(Aq ], \*(Aq2>\*(Aq, \e$err_out ); .Ve .Sp The subroutine will be called each time some data is read from the child. .Sp The >pipe operator is different in concept than the other '>' operators, although it's syntax is similar: .Sp .Vb 7 \& $h = start \e@cat, $in, \*(Aq>pipe\*(Aq, \e*OUT, \*(Aq2>pipe\*(Aq, \e*ERR; \& $in = "hello world\en"; \& finish $h; \& print <OUT>; \& print <ERR>; \& close OUT; \& close ERR; .Ve .Sp causes two pipe to be created, with one end attached to cat's stdout and stderr, respectively, and the other left open on \s-1OUT\s0 and \s-1ERR,\s0 so that the script can manually \&\fIread()\fR, \fIselect()\fR, etc. on them. This is like the behavior of IPC::Open2 and IPC::Open3. .Sp \&\fBWin32\fR: The handle returned is actually a socket handle, so you can use \fIselect()\fR on it. .IP "Duplicating output descriptors: >&m, n>&m" 4 .IX Item "Duplicating output descriptors: >&m, n>&m" This duplicates output descriptor number n (default is 1 if n is omitted) from descriptor number m. .IP "Duplicating input descriptors: <&m, n<&m" 4 .IX Item "Duplicating input descriptors: <&m, n<&m" This duplicates input descriptor number n (default is 0 if n is omitted) from descriptor number m .IP "Closing descriptors: <&\-, 3<&\-" 4 .IX Item "Closing descriptors: <&-, 3<&-" This closes descriptor number n (default is 0 if n is omitted). The following commands are equivalent: .Sp .Vb 3 \& run \e@cmd, \eundef; \& run \e@cmd, \*(Aq<&\-\*(Aq; \& run \e@cmd, \*(Aq<in.txt\*(Aq, \*(Aq<&\-\*(Aq; .Ve .Sp Doing .Sp .Vb 1 \& run \e@cmd, \e$in, \*(Aq<&\-\*(Aq; ## SIGPIPE recipe. .Ve .Sp is dangerous: the parent will get a \s-1SIGPIPE\s0 if \f(CW$in\fR is not empty. .IP "Redirecting both stdout and stderr: &>, >&, &>pipe, >pipe&" 4 .IX Item "Redirecting both stdout and stderr: &>, >&, &>pipe, >pipe&" The following pairs of commands are equivalent: .Sp .Vb 2 \& run \e@cmd, \*(Aq>&\*(Aq, \e$out; run \e@cmd, \*(Aq>\*(Aq, \e$out, \*(Aq2>&1\*(Aq; \& run \e@cmd, \*(Aq>&\*(Aq, \*(Aqout.txt\*(Aq; run \e@cmd, \*(Aq>\*(Aq, \*(Aqout.txt\*(Aq, \*(Aq2>&1\*(Aq; .Ve .Sp etc. .Sp File descriptor numbers are not permitted to the left or the right of these operators, and the '&' may occur on either end of the operator. .Sp The '&>pipe' and '>pipe&' variants behave like the '>pipe' operator, except that both stdout and stderr write to the created pipe. .IP "Redirection Filters" 4 .IX Item "Redirection Filters" Both input redirections and output redirections that use scalars or subs as endpoints may have an arbitrary number of filter subs placed between them and the child process. This is useful if you want to receive output in chunks, or if you want to massage each chunk of data sent to the child. To use this feature, you must use operator syntax: .Sp .Vb 5 \& run( \& \e@cmd \& \*(Aq<\*(Aq, \e&in_filter_2, \e&in_filter_1, $in, \& \*(Aq>\*(Aq, \e&out_filter_1, \e&in_filter_2, $out, \& ); .Ve .Sp This capability is not provided for \s-1IO\s0 handles or named files. .Sp Two filters are provided by IPC::Run: appender and chunker. Because these may take an argument, you need to use the constructor functions \&\fInew_appender()\fR and \fInew_chunker()\fR rather than using \e& syntax: .Sp .Vb 5 \& run( \& \e@cmd \& \*(Aq<\*(Aq, new_appender( "\en" ), $in, \& \*(Aq>\*(Aq, new_chunker, $out, \& ); .Ve .SS "Just doing I/O" .IX Subsection "Just doing I/O" If you just want to do I/O to a handle or file you open yourself, you may specify a filehandle or filename instead of a command in the harness specification: .PP .Vb 1 \& run io( "filename", \*(Aq>\*(Aq, \e$recv ); \& \& $h = start io( $io, \*(Aq>\*(Aq, \e$recv ); \& \& $h = harness \e@cmd, \*(Aq&\*(Aq, io( "file", \*(Aq<\*(Aq, \e$send ); .Ve .SS "Options" .IX Subsection "Options" Options are passed in as name/value pairs: .PP .Vb 1 \& run \e@cat, \e$in, debug => 1; .Ve .PP If you pass the debug option, you may want to pass it in first, so you can see what parsing is going on: .PP .Vb 1 \& run debug => 1, \e@cat, \e$in; .Ve .IP "debug" 4 .IX Item "debug" Enables debugging output in parent and child. Debugging info is emitted to the \s-1STDERR\s0 that was present when IPC::Run was first \f(CW\*(C`use()\*(C'\fRed (it's \&\f(CW\*(C`dup()\*(C'\fRed out of the way so that it can be redirected in children without having debugging output emitted on it). .SH "RETURN VALUES" .IX Header "RETURN VALUES" \&\fIharness()\fR and \fIstart()\fR return a reference to an IPC::Run harness. This is blessed in to the IPC::Run package, so you may make later calls to functions as members if you like: .PP .Vb 4 \& $h = harness( ... ); \& $h\->start; \& $h\->pump; \& $h\->finish; \& \& $h = start( .... ); \& $h\->pump; \& ... .Ve .PP Of course, using method call syntax lets you deal with any IPC::Run subclasses that might crop up, but don't hold your breath waiting for any. .PP \&\fIrun()\fR and \fIfinish()\fR return \s-1TRUE\s0 when all subcommands exit with a 0 result code. \fBThis is the opposite of perl's \f(BIsystem()\fB command\fR. .PP All routines raise exceptions (via \fIdie()\fR) when error conditions are recognized. A non-zero command result is not treated as an error condition, since some commands are tests whose results are reported in their exit codes. .SH "ROUTINES" .IX Header "ROUTINES" .RS 4 .IP "run" 4 .IX Item "run" Run takes a harness or harness specification and runs it, pumping all input to the child(ren), closing the input pipes when no more input is available, collecting all output that arrives, until the pipes delivering output are closed, then waiting for the children to exit and reaping their result codes. .Sp You may think of \f(CW\*(C`run( ... )\*(C'\fR as being like .Sp .Vb 1 \& start( ... )\->finish(); .Ve .Sp , though there is one subtle difference: \fIrun()\fR does not set \e$input_scalars to '' like \fIfinish()\fR does. If an exception is thrown from \fIrun()\fR, all children will be killed off \*(L"gently\*(R", and then \*(L"annihilated\*(R" if they do not go gently (in to that dark night. sorry). .Sp If any exceptions are thrown, this does a \*(L"kill_kill\*(R" before propagating them. .IP "signal" 4 .IX Item "signal" .Vb 3 \& ## To send it a specific signal by name ("USR1"): \& signal $h, "USR1"; \& $h\->signal ( "USR1" ); .Ve .Sp If \f(CW$signal\fR is provided and defined, sends a signal to all child processes. Try not to send numeric signals, use \f(CW"KILL"\fR instead of \f(CW9\fR, for instance. Numeric signals aren't portable. .Sp Throws an exception if \f(CW$signal\fR is undef. .Sp This will \fInot\fR clean up the harness, \f(CW\*(C`finish\*(C'\fR it if you kill it. .Sp Normally \s-1TERM\s0 kills a process gracefully (this is what the command line utility \&\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 \&\f(CW\*(C`<Del>\*(C'\fR, and \f(CW\*(C`QUIT\*(C'\fR is used to kill a process and make it coredump. .Sp The \f(CW\*(C`HUP\*(C'\fR signal is often used to get a process to \*(L"restart\*(R", rereading config files, and \f(CW\*(C`USR1\*(C'\fR and \f(CW\*(C`USR2\*(C'\fR for really application-specific things. .Sp Often, running \f(CW\*(C`kill \-l\*(C'\fR (that's a lower case \*(L"L\*(R") on the command line will list the signals present on your operating system. .Sp \&\fB\s-1WARNING\s0\fR: The signal subsystem is not at all portable. We *may* offer to simulate \f(CW\*(C`TERM\*(C'\fR and \f(CW\*(C`KILL\*(C'\fR on some operating systems, submit code to me if you want this. .Sp \&\fB\s-1WARNING 2\s0\fR: Up to and including perl v5.6.1, doing almost anything in a signal handler could be dangerous. The most safe code avoids all mallocs and system calls, usually by preallocating a flag before entering the signal handler, altering the flag's value in the handler, and responding to the changed value in the main system: .Sp .Vb 2 \& my $got_usr1 = 0; \& sub usr1_handler { ++$got_signal } \& \& $SIG{USR1} = \e&usr1_handler; \& while () { sleep 1; print "GOT IT" while $got_usr1\-\-; } .Ve .Sp Even this approach is perilous if ++ and \*(-- aren't atomic on your system (I've never heard of this on any modern \s-1CPU\s0 large enough to run perl). .IP "kill_kill" 4 .IX Item "kill_kill" .Vb 3 \& ## To kill off a process: \& $h\->kill_kill; \& kill_kill $h; \& \& ## To specify the grace period other than 30 seconds: \& kill_kill $h, grace => 5; \& \& ## To send QUIT instead of KILL if a process refuses to die: \& kill_kill $h, coup_d_grace => "QUIT"; .Ve .Sp Sends a \f(CW\*(C`TERM\*(C'\fR, waits for all children to exit for up to 30 seconds, then sends a \f(CW\*(C`KILL\*(C'\fR to any that survived the \f(CW\*(C`TERM\*(C'\fR. .Sp Will wait for up to 30 more seconds for the \s-1OS\s0 to successfully \f(CW\*(C`KILL\*(C'\fR the processes. .Sp The 30 seconds may be overridden by setting the \f(CW\*(C`grace\*(C'\fR option, this overrides both timers. .Sp The harness is then cleaned up. .Sp The doubled name indicates that this function may kill again and avoids colliding with the core Perl \f(CW\*(C`kill\*(C'\fR function. .Sp Returns a 1 if the \f(CW\*(C`TERM\*(C'\fR was sufficient, or a 0 if \f(CW\*(C`KILL\*(C'\fR was required. Throws an exception if \f(CW\*(C`KILL\*(C'\fR did not permit the children to be reaped. .Sp \&\fB\s-1NOTE\s0\fR: The grace period is actually up to 1 second longer than that given. This is because the granularity of \f(CW\*(C`time\*(C'\fR is 1 second. Let me know if you need finer granularity, we can leverage Time::HiRes here. .Sp \&\fBWin32\fR: Win32 does not know how to send real signals, so \f(CW\*(C`TERM\*(C'\fR is a full-force kill on Win32. Thus all talk of grace periods, etc. do not apply to Win32. .IP "harness" 4 .IX Item "harness" Takes a harness specification and returns a harness. This harness is blessed in to IPC::Run, allowing you to use method call syntax for \&\fIrun()\fR, \fIstart()\fR, et al if you like. .Sp \&\fIharness()\fR is provided so that you can pre-build harnesses if you would like to, but it's not required.. .Sp You may proceed to \fIrun()\fR, \fIstart()\fR or \fIpump()\fR after calling \fIharness()\fR (\fIpump()\fR calls \fIstart()\fR if need be). Alternatively, you may pass your harness specification to \fIrun()\fR or \fIstart()\fR and let them \fIharness()\fR for you. You can't pass harness specifications to \fIpump()\fR, though. .IP "close_terminal" 4 .IX Item "close_terminal" This is used as (or in) an init sub to cast off the bonds of a controlling terminal. It must precede all other redirection ops that affect \&\s-1STDIN, STDOUT,\s0 or \s-1STDERR\s0 to be guaranteed effective. .IP "start" 4 .IX Item "start" .Vb 5 \& $h = start( \& \e@cmd, \e$in, \e$out, ..., \& timeout( 30, name => "process timeout" ), \& $stall_timeout = timeout( 10, name => "stall timeout" ), \& ); \& \& $h = start \e@cmd, \*(Aq<\*(Aq, \e$in, \*(Aq|\*(Aq, \e@cmd2, ...; .Ve .Sp \&\fIstart()\fR accepts a harness or harness specification and returns a harness after building all of the pipes and launching (via \fIfork()\fR/\fIexec()\fR, or, maybe someday, \fIspawn()\fR) all the child processes. It does not send or receive any data on the pipes, see \fIpump()\fR and \fIfinish()\fR for that. .Sp You may call \fIharness()\fR and then pass it's result to \fIstart()\fR if you like, but you only need to if it helps you structure or tune your application. If you do call \fIharness()\fR, you may skip \fIstart()\fR and proceed directly to pump. .Sp \&\fIstart()\fR also starts all timers in the harness. See IPC::Run::Timer for more information. .Sp \&\fIstart()\fR flushes \s-1STDOUT\s0 and \s-1STDERR\s0 to help you avoid duplicate output. It has no way of asking Perl to flush all your open filehandles, so you are going to need to flush any others you have open. Sorry. .Sp Here's how if you don't want to alter the state of $| for your filehandle: .Sp .Vb 1 \& $ofh = select HANDLE; $of = $|; $| = 1; $| = $of; select $ofh; .Ve .Sp If you don't mind leaving output unbuffered on \s-1HANDLE,\s0 you can do the slightly shorter .Sp .Vb 1 \& $ofh = select HANDLE; $| = 1; select $ofh; .Ve .Sp Or, you can use IO::Handle's \fIflush()\fR method: .Sp .Vb 2 \& use IO::Handle; \& flush HANDLE; .Ve .Sp Perl needs the equivalent of C's fflush( (\s-1FILE\s0 *)NULL ). .IP "adopt" 4 .IX Item "adopt" Experimental feature. \s-1NOT FUNCTIONAL YET, NEED TO CLOSE FDS BETTER IN CHILDREN. SEE\s0 t/adopt.t for a test suite. .IP "pump" 4 .IX Item "pump" .Vb 2 \& pump $h; \& $h\->pump; .Ve .Sp Pump accepts a single parameter harness. It blocks until it delivers some input or receives some output. It returns \s-1TRUE\s0 if there is still input or output to be done, \s-1FALSE\s0 otherwise. .Sp \&\fIpump()\fR will automatically call \fIstart()\fR if need be, so you may call \fIharness()\fR then proceed to \fIpump()\fR if that helps you structure your application. .Sp If \fIpump()\fR is called after all harnessed activities have completed, a \*(L"process ended prematurely\*(R" exception to be thrown. This allows for simple scripting of external applications without having to add lots of error handling code at each step of the script: .Sp .Vb 1 \& $h = harness \e@smbclient, \e$in, \e$out, $err; \& \& $in = "cd /foo\en"; \& $h\->pump until $out =~ /^smb.*> \eZ/m; \& die "error cding to /foo:\en$out" if $out =~ "ERR"; \& $out = \*(Aq\*(Aq; \& \& $in = "mget *\en"; \& $h\->pump until $out =~ /^smb.*> \eZ/m; \& die "error retrieving files:\en$out" if $out =~ "ERR"; \& \& $h\->finish; \& \& warn $err if $err; .Ve .IP "pump_nb" 4 .IX Item "pump_nb" .Vb 2 \& pump_nb $h; \& $h\->pump_nb; .Ve .Sp \&\*(L"\fIpump()\fR non-blocking\*(R", pumps if anything's ready to be pumped, returns immediately otherwise. This is useful if you're doing some long-running task in the foreground, but don't want to starve any child processes. .IP "pumpable" 4 .IX Item "pumpable" Returns \s-1TRUE\s0 if calling \fIpump()\fR won't throw an immediate \*(L"process ended prematurely\*(R" exception. This means that there are open I/O channels or active processes. May yield the parent processes' time slice for 0.01 second if all pipes are to the child and all are paused. In this case we can't tell if the child is dead, so we yield the processor and then attempt to reap the child in a nonblocking way. .IP "reap_nb" 4 .IX Item "reap_nb" Attempts to reap child processes, but does not block. .Sp Does not currently take any parameters, one day it will allow specific children to be reaped. .Sp Only call this from a signal handler if your \f(CW\*(C`perl\*(C'\fR is recent enough to have safe signal handling (5.6.1 did not, \s-1IIRC,\s0 but it was being discussed on perl5\-porters). Calling this (or doing any significant work) in a signal handler on older \f(CW\*(C`perl\*(C'\fRs is asking for seg faults. .IP "finish" 4 .IX Item "finish" This must be called after the last \fIstart()\fR or \fIpump()\fR call for a harness, or your system will accumulate defunct processes and you may \*(L"leak\*(R" file descriptors. .Sp \&\fIfinish()\fR returns \s-1TRUE\s0 if all children returned 0 (and were not signaled and did not coredump, ie ! $?), and \s-1FALSE\s0 otherwise (this is like \fIrun()\fR, and the opposite of \fIsystem()\fR). .Sp Once a harness has been finished, it may be \fIrun()\fR or \fIstart()\fRed again, including by \fIpump()\fRs auto-start. .Sp If this throws an exception rather than a normal exit, the harness may be left in an unstable state, it's best to kill the harness to get rid of all the child processes, etc. .Sp Specifically, if a timeout expires in \fIfinish()\fR, \fIfinish()\fR will not kill all the children. Call \f(CW\*(C`<$h\-\*(C'\fRkill_kill>> in this case if you care. This differs from the behavior of \*(L"run\*(R". .IP "result" 4 .IX Item "result" .Vb 1 \& $h\->result; .Ve .Sp Returns the first non-zero result code (ie $? >> 8). See \*(L"full_result\*(R" to get the $? value for a child process. .Sp To get the result of a particular child, do: .Sp .Vb 2 \& $h\->result( 0 ); # first child\*(Aqs $? >> 8 \& $h\->result( 1 ); # second child .Ve .Sp or .Sp .Vb 2 \& ($h\->results)[0] \& ($h\->results)[1] .Ve .Sp Returns undef if no child processes were spawned and no child number was specified. Throws an exception if an out-of-range child number is passed. .IP "results" 4 .IX Item "results" Returns a list of child exit values. See \*(L"full_results\*(R" if you want to know if a signal killed the child. .Sp Throws an exception if the harness is not in a finished state. .IP "full_result" 4 .IX Item "full_result" .Vb 1 \& $h\->full_result; .Ve .Sp Returns the first non-zero $?. See \*(L"result\*(R" to get the first $? >> 8 value for a child process. .Sp To get the result of a particular child, do: .Sp .Vb 2 \& $h\->full_result( 0 ); # first child\*(Aqs $? >> 8 \& $h\->full_result( 1 ); # second child .Ve .Sp or .Sp .Vb 2 \& ($h\->full_results)[0] \& ($h\->full_results)[1] .Ve .Sp Returns undef if no child processes were spawned and no child number was specified. Throws an exception if an out-of-range child number is passed. .IP "full_results" 4 .IX Item "full_results" Returns a list of child exit values as returned by \f(CW\*(C`wait\*(C'\fR. See \*(L"results\*(R" if you don't care about coredumps or signals. .Sp Throws an exception if the harness is not in a finished state. .RE .RS 4 .RE .SH "FILTERS" .IX Header "FILTERS" These filters are used to modify input our output between a child process and a scalar or subroutine endpoint. .IP "binary" 4 .IX Item "binary" .Vb 3 \& run \e@cmd, ">", binary, \e$out; \& run \e@cmd, ">", binary, \e$out; ## Any TRUE value to enable \& run \e@cmd, ">", binary 0, \e$out; ## Any FALSE value to disable .Ve .Sp This is a constructor for a \*(L"binmode\*(R" \*(L"filter\*(R" that tells IPC::Run to keep the carriage returns that would ordinarily be edited out for you (binmode is usually off). This is not a real filter, but an option masquerading as a filter. .Sp It's not named \*(L"binmode\*(R" because you're likely to want to call Perl's binmode in programs that are piping binary data around. .IP "new_chunker" 4 .IX Item "new_chunker" This breaks a stream of data in to chunks, based on an optional scalar or regular expression parameter. The default is the Perl input record separator in $/, which is a newline be default. .Sp .Vb 2 \& run \e@cmd, \*(Aq>\*(Aq, new_chunker, \e&lines_handler; \& run \e@cmd, \*(Aq>\*(Aq, new_chunker( "\er\en" ), \e&lines_handler; .Ve .Sp Because this uses $/ by default, you should always pass in a parameter if you are worried about other code (modules, etc) modifying $/. .Sp If this filter is last in a filter chain that dumps in to a scalar, the scalar must be set to '' before a new chunk will be written to it. .Sp As an example of how a filter like this can be written, here's a chunker that splits on newlines: .Sp .Vb 2 \& sub line_splitter { \& my ( $in_ref, $out_ref ) = @_; \& \& return 0 if length $$out_ref; \& \& return input_avail && do { \& while (1) { \& if ( $$in_ref =~ s/\eA(.*?\en)// ) { \& $$out_ref .= $1; \& return 1; \& } \& my $hmm = get_more_input; \& unless ( defined $hmm ) { \& $$out_ref = $$in_ref; \& $$in_ref = \*(Aq\*(Aq; \& return length $$out_ref ? 1 : 0; \& } \& return 0 if $hmm eq 0; \& } \& } \& }; .Ve .IP "new_appender" 4 .IX Item "new_appender" This appends a fixed string to each chunk of data read from the source scalar or sub. This might be useful if you're writing commands to a child process that always must end in a fixed string, like \*(L"\en\*(R": .Sp .Vb 3 \& run( \e@cmd, \& \*(Aq<\*(Aq, new_appender( "\en" ), \e&commands, \& ); .Ve .Sp Here's a typical filter sub that might be created by \fInew_appender()\fR: .Sp .Vb 2 \& sub newline_appender { \& my ( $in_ref, $out_ref ) = @_; \& \& return input_avail && do { \& $$out_ref = join( \*(Aq\*(Aq, $$out_ref, $$in_ref, "\en" ); \& $$in_ref = \*(Aq\*(Aq; \& 1; \& } \& }; .Ve .IP "new_string_source" 4 .IX Item "new_string_source" \&\s-1TODO:\s0 Needs confirmation. Was previously undocumented. in this module. .Sp 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. .Sp \&\s-1NOTE:\s0 Any additional variables passed to new_string_source will be passed to the sub every time it's called and appended to the output. .IP "new_string_sink" 4 .IX Item "new_string_sink" \&\s-1TODO:\s0 Needs confirmation. Was previously undocumented. .Sp 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. .IP "io" 4 .IX Item "io" Takes a filename or filehandle, a redirection operator, optional filters, and a source or destination (depends on the redirection operator). Returns an IPC::Run::IO object suitable for \fIharness()\fRing (including via \fIstart()\fR or \fIrun()\fR). .Sp This is shorthand for .Sp .Vb 1 \& require IPC::Run::IO; \& \& ... IPC::Run::IO\->new(...) ... .Ve .IP "timer" 4 .IX Item "timer" .Vb 1 \& $h = start( \e@cmd, \e$in, \e$out, $t = timer( 5 ) ); \& \& pump $h until $out =~ /expected stuff/ || $t\->is_expired; .Ve .Sp Instantiates a non-fatal timer. \fIpump()\fR returns once each time a timer expires. Has no direct effect on \fIrun()\fR, but you can pass a subroutine to fire when the timer expires. .Sp See \*(L"timeout\*(R" for building timers that throw exceptions on expiration. .Sp See \*(L"timer\*(R" in IPC::Run::Timer for details. .IP "timeout" 4 .IX Item "timeout" .Vb 1 \& $h = start( \e@cmd, \e$in, \e$out, $t = timeout( 5 ) ); \& \& pump $h until $out =~ /expected stuff/; .Ve .Sp Instantiates a timer that throws an exception when it expires. If you don't provide an exception, a default exception that matches /^IPC::Run: .*timed out/ is thrown by default. You can pass in your own exception scalar or reference: .Sp .Vb 4 \& $h = start( \& \e@cmd, \e$in, \e$out, \& $t = timeout( 5, exception => \*(Aqslowpoke\*(Aq ), \& ); .Ve .Sp or set the name used in debugging message and in the default exception string: .Sp .Vb 5 \& $h = start( \& \e@cmd, \e$in, \e$out, \& timeout( 50, name => \*(Aqprocess timer\*(Aq ), \& $stall_timer = timeout( 5, name => \*(Aqstall timer\*(Aq ), \& ); \& \& pump $h until $out =~ /started/; \& \& $in = \*(Aqcommand 1\*(Aq; \& $stall_timer\->start; \& pump $h until $out =~ /command 1 finished/; \& \& $in = \*(Aqcommand 2\*(Aq; \& $stall_timer\->start; \& pump $h until $out =~ /command 2 finished/; \& \& $in = \*(Aqvery slow command 3\*(Aq; \& $stall_timer\->start( 10 ); \& pump $h until $out =~ /command 3 finished/; \& \& $stall_timer\->start( 5 ); \& $in = \*(Aqcommand 4\*(Aq; \& pump $h until $out =~ /command 4 finished/; \& \& $stall_timer\->reset; # Prevent restarting or expirng \& finish $h; .Ve .Sp See \*(L"timer\*(R" for building non-fatal timers. .Sp See \*(L"timer\*(R" in IPC::Run::Timer for details. .SH "FILTER IMPLEMENTATION FUNCTIONS" .IX Header "FILTER IMPLEMENTATION FUNCTIONS" These functions are for use from within filters. .IP "input_avail" 4 .IX Item "input_avail" Returns \s-1TRUE\s0 if input is available. If none is available, then &get_more_input is called and its result is returned. .Sp This is usually used in preference to &get_more_input so that the calling filter removes all data from the \f(CW$in_ref\fR before more data gets read in to \f(CW$in_ref\fR. .Sp \&\f(CW\*(C`input_avail\*(C'\fR is usually used as part of a return expression: .Sp .Vb 4 \& return input_avail && do { \& ## process the input just gotten \& 1; \& }; .Ve .Sp This technique allows input_avail to return the undef or 0 that a filter normally returns when there's no input to process. If a filter stores intermediate values, however, it will need to react to an undef: .Sp .Vb 7 \& my $got = input_avail; \& if ( ! defined $got ) { \& ## No more input ever, flush internal buffers to $out_ref \& } \& return $got unless $got; \& ## Got some input, move as much as need be \& return 1 if $added_to_out_ref; .Ve .IP "get_more_input" 4 .IX Item "get_more_input" This is used to fetch more input in to the input variable. It returns undef if there will never be any more input, 0 if there is none now, but there might be in the future, and \s-1TRUE\s0 if more input was gotten. .Sp \&\f(CW\*(C`get_more_input\*(C'\fR is usually used as part of a return expression, see \*(L"input_avail\*(R" for more information. .SH "TODO" .IX Header "TODO" These will be addressed as needed and as time allows. .PP Stall timeout. .PP Expose a list of child process objects. When I do this, each child process is likely to be blessed into IPC::Run::Proc. .PP \&\f(CW$kid\fR\->\fIabort()\fR, \f(CW$kid\fR\->\fIkill()\fR, \f(CW$kid\fR\->signal( \f(CW$num_or_name\fR ). .PP Write tests for /(full_)?results?/ subs. .PP Currently, \fIpump()\fR and \fIrun()\fR only work on systems where \fIselect()\fR works on the filehandles returned by \fIpipe()\fR. This does *not* include ActiveState on Win32, although it does work on cygwin under Win32 (thought the tests whine a bit). I'd like to rectify that, suggestions and patches welcome. .PP Likewise \fIstart()\fR only fully works on \fIfork()\fR/\fIexec()\fR machines (well, just \&\fIfork()\fR if you only ever pass perl subs as subprocesses). There's some scaffolding for calling \fIOpen3::spawn_with_handles()\fR, but that's untested, and not that useful with limited \fIselect()\fR. .PP Support for \f(CW\*(C`\e@sub_cmd\*(C'\fR as an argument to a command which gets replaced with /dev/fd or the name of a temporary file containing foo's output. This is like <(sub_cmd ...) found in bash and csh (\s-1IIRC\s0). .PP Allow multiple harnesses to be combined as independent sets of processes in to one 'meta\-harness'. .PP Allow a harness to be passed in place of an \e@cmd. This would allow multiple harnesses to be aggregated. .PP Ability to add external file descriptors w/ filter chains and endpoints. .PP Ability to add timeouts and timing generators (i.e. repeating timeouts). .PP High resolution timeouts. .SH "Win32 LIMITATIONS" .IX Header "Win32 LIMITATIONS" .IP "Fails on Win9X" 4 .IX Item "Fails on Win9X" If you want Win9X support, you'll have to debug it or fund me because I don't use that system any more. The Win32 subsysem has been extended to use temporary files in simple \fIrun()\fR invocations and these may actually work on Win9X too, but I don't have time to work on it. .IP "May deadlock on Win2K (but not WinNT4 or WinXPPro)" 4 .IX Item "May deadlock on Win2K (but not WinNT4 or WinXPPro)" Spawning more than one subprocess on Win2K causes a deadlock I haven't figured out yet, but simple uses of \fIrun()\fR often work. Passes all tests on WinXPPro and WinNT. .IP "no support yet for <pty< and >pty>" 4 .IX Item "no support yet for <pty< and >pty>" These are likely to be implemented as \*(L"<\*(R" and \*(L">\*(R" with binmode on, not sure. .IP "no support for file descriptors higher than 2 (stderr)" 4 .IX Item "no support for file descriptors higher than 2 (stderr)" Win32 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 get the integer handle and pass it to the child process using the command line, environment, stdin, intermediary file, or other \s-1IPC\s0 mechanism. Then use that handle in the child (Win32API.pm provides ways to reconstitute Perl file handles from Win32 file handles). .IP "no support for subroutine subprocesses (\s-1CODE\s0 refs)" 4 .IX Item "no support for subroutine subprocesses (CODE refs)" Can't \fIfork()\fR, so the subroutines would have no context, and closures certainly have no meaning .Sp Perhaps with Win32 \fIfork()\fR emulation, this can be supported in a limited fashion, but there are other very serious problems with that: all parent fds get \fIdup()\fRed in to the thread emulating the forked process, and that keeps the parent from being able to close all of the appropriate fds. .IP "no support for init => sub {} routines." 4 .IX Item "no support for init => sub {} routines." Win32 processes are created from scratch, there is no way to do an init routine that will affect the running child. Some limited support might be implemented one day, do \fIchdir()\fR and \f(CW%ENV\fR changes can be made. .IP "signals" 4 .IX Item "signals" Win32 does not fully support signals. \fIsignal()\fR is likely to cause errors unless sending a signal that Perl emulates, and \f(CW\*(C`kill_kill()\*(C'\fR is immediately fatal (there is no grace period). .IP "helper processes" 4 .IX Item "helper processes" IPC::Run uses helper processes, one per redirected file, to adapt between the anonymous pipe connected to the child and the \s-1TCP\s0 socket connected to the parent. This is a waste of resources and will change in the future to either use threads (instead of helper processes) or a WaitForMultipleObjects call (instead of select). Please contact me if you can help with the \&\fIWaitForMultipleObjects()\fR approach; I haven't figured out how to get at it without C code. .IP "shutdown pause" 4 .IX Item "shutdown pause" There seems to be a pause of up to 1 second between when a child program exits and the corresponding sockets indicate that they are closed in the parent. Not sure why. .IP "binmode" 4 .IX Item "binmode" binmode is not supported yet. The underpinnings are implemented, just ask if you need it. .IP "IPC::Run::IO" 4 .IX Item "IPC::Run::IO" IPC::Run::IO objects can be used on Unix to read or write arbitrary files. On Win32, they will need to use the same helper processes to adapt from non\-\fIselect()\fRable filehandles to \fIselect()\fRable ones (or perhaps \&\fIWaitForMultipleObjects()\fR will work with them, not sure). .IP "startup race conditions" 4 .IX Item "startup race conditions" There seems to be an occasional race condition between child process startup and pipe closings. It seems like if the child is not fully created by the time CreateProcess returns and we close the \s-1TCP\s0 socket being handed to it, the parent socket can also get closed. This is seen with the Win32 pumper applications, not the \*(L"real\*(R" child process being spawned. .Sp I assume this is because the kernel hasn't gotten around to incrementing the reference count on the child's end (since the child was slow in starting), so the parent's closing of the child end causes the socket to be closed, thus closing the parent socket. .Sp Being a race condition, it's hard to reproduce, but I encountered it while testing this code on a drive share to a samba box. In this case, it takes t/run.t a long time to spawn it's chile processes (the parent hangs in the first select for several seconds until the child emits any debugging output). .Sp I have not seen it on local drives, and can't reproduce it at will, unfortunately. The symptom is a \*(L"bad file descriptor in \fIselect()\fR\*(R" error, and, by turning on debugging, it's possible to see that \fIselect()\fR is being called on a no longer open file descriptor that was returned from the \fI_socket()\fR routine in Win32Helper. There's a new \fIconfess()\fR that checks for this (\*(L"\s-1PARENT_HANDLE\s0 no longer open\*(R"), but I haven't been able to reproduce it (typically). .SH "LIMITATIONS" .IX Header "LIMITATIONS" On Unix, requires a system that supports \f(CW\*(C`waitpid( $pid, WNOHANG )\*(C'\fR so it can tell if a child process is still running. .PP PTYs don't seem to be non-blocking on some versions of Solaris. Here's a test script contributed by Borislav Deianov <borislav@ensim.com> to see if you have the problem. If it dies, you have the problem. .PP .Vb 1 \& #!/usr/bin/perl \& \& use IPC::Run qw(run); \& use Fcntl; \& use IO::Pty; \& \& sub makecmd { \& return [\*(Aqperl\*(Aq, \*(Aq\-e\*(Aq, \& \*(Aq<STDIN>, print "\en" x \*(Aq.$_[0].\*(Aq; while(<STDIN>){last if /end/}\*(Aq]; \& } \& \& #pipe R, W; \& #fcntl(W, F_SETFL, O_NONBLOCK); \& #while (syswrite(W, "\en", 1)) { $pipebuf++ }; \& #print "pipe buffer size is $pipebuf\en"; \& my $pipebuf=4096; \& my $in = "\en" x ($pipebuf * 2) . "end\en"; \& my $out; \& \& $SIG{ALRM} = sub { die "Never completed!\en" }; \& \& print "reading from scalar via pipe..."; \& alarm( 2 ); \& run(makecmd($pipebuf * 2), \*(Aq<\*(Aq, \e$in, \*(Aq>\*(Aq, \e$out); \& alarm( 0 ); \& print "done\en"; \& \& print "reading from code via pipe... "; \& alarm( 2 ); \& run(makecmd($pipebuf * 3), \*(Aq<\*(Aq, sub { $t = $in; undef $in; $t}, \*(Aq>\*(Aq, \e$out); \& alarm( 0 ); \& print "done\en"; \& \& $pty = IO::Pty\->new(); \& $pty\->blocking(0); \& $slave = $pty\->slave(); \& while ($pty\->syswrite("\en", 1)) { $ptybuf++ }; \& print "pty buffer size is $ptybuf\en"; \& $in = "\en" x ($ptybuf * 3) . "end\en"; \& \& print "reading via pty... "; \& alarm( 2 ); \& run(makecmd($ptybuf * 3), \*(Aq<pty<\*(Aq, \e$in, \*(Aq>\*(Aq, \e$out); \& alarm(0); \& print "done\en"; .Ve .PP No support for ';', '&&', '||', '{ ... }', etc: use perl's, since \fIrun()\fR returns \s-1TRUE\s0 when the command exits with a 0 result code. .PP Does not provide shell-like string interpolation. .PP No 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 .PP .Vb 8 \& run( \& \ecmd, \& ... \& init => sub { \& chdir $dir or die $!; \& $ENV{FOO}=\*(AqBAR\*(Aq \& } \& ); .Ve .PP Timeout calculation does not allow absolute times, or specification of days, months, etc. .PP \&\fB\s-1WARNING:\s0\fR Function coprocesses (\f(CW\*(C`run \e&foo, ...\*(C'\fR) suffer from two limitations. The first is that it is difficult to close all filehandles the child inherits from the parent, since there is no way to scan all open FILEHANDLEs in Perl and it both painful and a bit dangerous to close all open file descriptors with \f(CW\*(C`POSIX::close()\*(C'\fR. Painful because we can't tell which fds are open at the \s-1POSIX\s0 level, either, so we'd have to scan all possible fds and close any that we don't want open (normally \f(CW\*(C`exec()\*(C'\fR closes any non-inheritable but we don't \f(CW\*(C`exec()\*(C'\fR for &sub processes. .PP The second problem is that Perl's \s-1DESTROY\s0 subs and other on-exit cleanup gets run in the child process. If objects are instantiated in the parent before the child is forked, the \s-1DESTROY\s0 will get run once in the parent and once in the child. When coprocess subs exit, POSIX::exit is called to work around this, but it means that objects that are still referred to at that time are not cleaned up. So setting package vars or closure vars to point to objects that rely on \s-1DESTROY\s0 to affect things outside the process (files, etc), will lead to bugs. .PP I goofed on the syntax: \*(L"<pipe\*(R" vs. \*(L"<pty<\*(R" and \*(L">filename\*(R" are both oddities. .SH "TODO" .IX Header "TODO" .ie n .IP "Allow one harness to ""adopt"" another:" 4 .el .IP "Allow one harness to ``adopt'' another:" 4 .IX Item "Allow one harness to adopt another:" .Vb 2 \& $new_h = harness \e@cmd2; \& $h\->adopt( $new_h ); .Ve .IP "Close all filehandles not explicitly marked to stay open." 4 .IX Item "Close all filehandles not explicitly marked to stay open." The problem with this one is that there's no good way to scan all open FILEHANDLEs in Perl, yet you don't want child processes inheriting handles willy-nilly. .SH "INSPIRATION" .IX Header "INSPIRATION" Well, \fIselect()\fR and \fIwaitpid()\fR badly needed wrapping, and \fIopen3()\fR isn't open-minded enough for me. .PP The shell-like \s-1API\s0 inspired by a message Russ Allbery sent to perl5\-porters, which included: .PP .Vb 4 \& I\*(Aqve thought for some time that it would be \& nice to have a module that could handle full Bourne shell pipe syntax \& internally, with fork and exec, without ever invoking a shell. Something \& that you could give things like: \& \& pipeopen (PIPE, [ qw/cat file/ ], \*(Aq|\*(Aq, [ \*(Aqanalyze\*(Aq, @args ], \*(Aq>&3\*(Aq); .Ve .PP Message ylln51p2b6.fsf@windlord.stanford.edu, on 2000/02/04. .SH "SUPPORT" .IX Header "SUPPORT" Bugs should always be submitted via the \s-1CPAN\s0 bug tracker .PP <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=IPC\-Run> .PP For other issues, contact the maintainer (the first listed author) .SH "AUTHORS" .IX Header "AUTHORS" Adam Kennedy <adamk@cpan.org> .PP Barrie Slaymaker <barries@slaysys.com> .SH "COPYRIGHT" .IX Header "COPYRIGHT" Some parts copyright 2008 \- 2009 Adam Kennedy. .PP Copyright 1999 Barrie Slaymaker. .PP You may distribute under the terms of either the \s-1GNU\s0 General Public License or the Artistic License, as specified in the \s-1README\s0 file.