NAME
Run - start programs in the background, and run command trees (and, or, chains, pipelines, redirections) without a shell
SYNOPSIS
use Run; # exports spawn
my $pid = spawn 'long_running_task', 'arg1', 'arg2' or die "spawn: $!";
do_something_else();
waitpid $pid, 0;
use Run ':NEW'; # the command trees
my $tree = new_pipeline(new_system('sort'),
new_redir([1 => {filename => 'out.txt', mode => '>'}],
new_system('uniq', '-c')));
my %data = (errs => []);
$tree->run(\%data) or warn "status $data{result}: @{$data{errs}}";
# one program, its redirections applied as sh would (public since 0.07)
my @errs;
my $kid = Run::start(1, ['prog', 'arg'],
[1 => {filename => 'log', mode => '>>'}, 2 => {fd => 1}],
\@errs);
DESCRIPTION
Run starts programs with redirections, without a shell, on systems with fork and on systems with a native spawn but no fork (Win32, OS/2, VMS; see "FORKLESS"). It has three layers:
spawn-
like the builtin
system, but the program runs in the background (see "spawn"); - command trees
-
nodes for simple commands,
&&,||,;, pipelines, pipes to and from this process, command substitution, environment settings and redirections, whichrunas sh would run the same command line (see "COMMAND TREES"); Run::start-
one program with a list of redirections (see "STARTING ONE PROGRAM"), the layer the others are built on; Proc::Spawner uses it where there is neither posix_spawn nor
fork.
EXPORT
spawn by default; the tag :NEW exports the constructors new_system, new_spawn, new_and, new_or, new_chain, new_env, new_redir, new_pipe, new_pipeline, new_readpipe and new_readpipe_split.
spawn
spawn LIST starts LIST as the builtin system LIST would (a single string is a command line for the shell; more elements, a program and its arguments) and returns the kid's pid at once; the caller waits for it with waitpid. Without fork it is system 1, LIST (P_NOWAIT). When nothing was started it returns undef, with $! set.
COMMAND TREES
A tree is built of these nodes (CMD is a node):
new_system(PROG, ARGS...)-
runs PROG with ARGS and waits for it. PROG and ARGS are never a shell command line: a single element is a program name (as
system { PROG } PROG, ARGS). An element that is itself a node (new_readpipe,new_readpipe_split) is replaced by that node's output first, as a command substitution is. new_spawn(PROG, ARGS...)-
the same, without waiting: the kid's pid is pushed on
$data->{pids}. new_and(CMD...),new_or(CMD...),new_chain(CMD...)-
CMD && CMD ...,CMD || CMD ...andCMD; CMD .... They wait for each command, so they cannot run undernew_spawnornew_pipe. new_env({NAME => VALUE, ...}, CMD)-
CMD with these variables added to its environment.
new_redir(REDIRS, CMD)-
CMD with these redirections (see "REDIRECTIONS"), applied after the outer ones, as in sh's
{ CMD 2>&1; } >f. new_pipeline(CMD...)-
CMD | CMD | ...; see "PIPELINES". new_pipe('r' or 'w', CMD)-
starts CMD (a simple command) with its fd 1 (
'r') or fd 0 ('w') on a pipe, andrunreturns this process's end of it as a handle. The kid's pid is pushed on$data->{pids}; the caller waits for it. new_readpipe(CMD),new_readpipe_split(CMD)-
runreturns CMD's whole output (trailing newlines kept), or that output split at whitespace; the kid is waited for. As an argument ofnew_systemthey are command substitutions.
$tree->run(\%DATA) runs a tree; %DATA (optional) passes:
errs => \@ERRS-
the messages (a program or a file that could not be opened, ...) are pushed here; without it they are printed on STDERR.
env => {...},redir => REDIRS-
variables and redirections for every command of the tree.
pids => \@PIDS-
receives the pids of
new_spawnandnew_pipekids. result-
set by
run: the$?of the last command that ran, 0 included, or -1 when nothing was started (the program or a redirection target could not be opened; the reason is inerrs).
run returns true iff the command succeeded (new_pipe: the handle; new_readpipe: the output). After new_and, new_or, new_chain and new_pipeline, result holds the status sh would give; new_chain succeeds iff its last command does, as in sh.
PIPELINES
new_pipeline(CMD1, CMD2, ...) is CMD1 | CMD2 | .... An element that is a simple command (new_system or new_spawn, possibly under new_env and new_redir) is spawned with the pipe ends as fds 0 and 1: after the outer redirections and before its own, as in sh.
Any other element (new_and, new_or, new_chain, a nested new_pipeline) runs in this process, after every other element has started, with the pipe ends applied to each command it starts. This process keeps its write end open until the element's last command has ended, so in { A || B } | C the reader sees one stream: B starts (or not) when A has ended, and C sees end of file only after that. Before running it, this process closes every other pipe end, so readers see end of file and writers get SIGPIPE as in sh.
Only one element can run in this process (the last such one). Where fork exists, the others run in forked copies of this process, which exit with the status of their last command (255 if it died); their messages, and the message of a die, come back into errs. With $Run::Forkless a second such element is refused. If the element run in this process dies, the pipeline closes its pipes, reaps its kids and then rethrows.
The pipeline succeeds iff its last element does; $data->{result} is the last element's status, or -1 if it did not start or nothing could be started (a pipe could not be created, a refused element). An element that did not start is reported in errs and the others run on. The pipeline cannot itself run under spawn (as a new_pipe element).
REDIRECTIONS
new_redir, run({redir => ...}) and Run::start take either a hash {FD => SPEC}, applied in increasing FD, or an array [FD => SPEC, ...], applied in the order given. As in sh, redirections are applied left to right, outer new_redir first, so [1 => {filename => 'f', mode => '>'}, 2 => {fd => 1}] is >f 2>&1, and the reverse order is 2>&1 >f. SPEC is one of:
{filename => NAME, mode => OP}-
NAME is the file's name as it is (
-,&1and leading blanks are literal), opened as sh's OP does:<reads,>and>|create or truncate,>>appends,<>reads and writes, creating the file but not truncating it. FD becomes a copy of that file. Use this form for names that come from elsewhere. {fd => M}(since 0.07),{filehandle => FH}-
FD becomes a copy of fd M (or
fileno FH) as it is at that point, so an earlier redirection of that fd counts: sh'sFD>&M. {close => 1}(since 0.07)-
FD is closed in the kid: sh's
FD>&-. {filehandle => FH, pin => 1}-
FD becomes a copy of FH's file, even when
fileno FHis itself one of the target fds: FH is first copied above every target. This is the safe way to pass a file the caller opened, or a pipe end. {filename => STRING}-
the older form:
'>&N'(or'>&=N','<&N') is{fd => N},'>&-'(or'<&-') is{close => 1}; any other STRING is opened with 2-argumentopen(so-means STDIN or STDOUT, leading blanks are dropped, and so on), and FD becomes a copy of that file.
Where fork exists, the redirections are applied in the kid between fork and exec, and the parent's fd table is never changed. Where it does not (forkless, see below), they are applied in the parent around a spawn that inherits the fd table, and afterwards every target fd is put back as it was: open on the same file with the same close-on-exec flag, or closed.
STARTING ONE PROGRAM
Run::start(SPAWN, \@ARGS, REDIRS, \@ERRS, PROG) (public since 0.07) runs the program @ARGS (never a shell command line) with REDIRS applied (see "REDIRECTIONS"; files it opens for them are closed again after the start). PROG (optional) is the program to run when it is not $ARGS[0], as system { PROG } LIST. Returns the pid when SPAWN is true, else $?; when nothing was started, undef (SPAWN) or -1, with $! set and a message pushed on @ERRS.
FORKLESS
On OS/2, Win32 and VMS $Run::Forkless is true, and Run starts every process with one primitive, Run::spawn_nowait(LIST_FLAG, \@ARGS, \@ERRS, PROG): like spawnvp(P_NOWAIT), the kid gets this process's fd table as it is (except close-on-exec fds), and the pid is returned (undef, with a message, if nothing started). There it is system { PROG } 1, ARGS (with a false LIST_FLAG, system 1, ARGS, whose single string is a command line). Nothing else in Run forks; new_system is spawn_nowait followed by waitpid.
On Unix, which has no spawn, the primitive is emulated by fork and exec with nothing in between. Setting $Run::Forkless (local is fine; $Run::Wraparound is the old name, and either one set means forkless) runs the forkless code paths there, which is how they are tested.
Limits of the parent-side way: other threads see the redirected fds while the kid starts; and outside Linux and Win32 the close-on-exec flag of a target fd is inferred, not read (Perl cannot look at it without changing it), so a fd opened by C code with the flag set comes back without it.
Win32
Perl's own spawn passes a kid fds 0..2 only (as its standard handles), and in a new process group; at most 64 kids can be running at once (Perl's table of children: then EAGAIN). Perl has no fcntl there: close-on-exec is the handle's inheritance, read and set through Win32API::File (which comes with Perl there; since 0.07). A kid's arguments go through Perl's command line, which does not quote them as the kid's C runtime parses them back: an argument with " or a trailing \ does not arrive as given (a bug of Perl's; the test is TODO). Tested under Wine with Strawberry Perl 5.38.2; OS/2 and VMS are not tested.
$Run::AsWin32 (true on Win32) selects these code paths: copies made by dup instead of F_DUPFD, no alias handles while fds are saved, the flag read and set through os_inherit(). Set it on Unix (or RUN_AS_WIN32=1 in the environment, before Run is loaded) to debug and test them there: FD_CLOEXEC then stands in for the handle's inheritance, so all but the Win32API::File calls themselves run. t/as-win32.t runs every test file so.
NOTES
open FH, ">&=FH1" creates a "naughty" copy of FH1. Closing FH will invalidate FH1 -- unless another Perl handle also uses that fd: PerlIO counts the handles of each fd. Such an open also sets or clears close-on-exec on that fd according to $^F.
TODO
The messages of the commands of new_or that failed stay in errs when a later one succeeds; should they be cleared?
AUTHOR
Ilya Zakharevich <ilyaz@cpan.org>
COPYRIGHT AND LICENSE
Copyright (C) 1997-2026 by Ilya Zakharevich.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. That is, at your choice, under the GNU General Public License as published by the Free Software Foundation (version 1, or any later version), or under the Artistic License that comes with Perl (see perlartistic and perlgpl).