Perl processes
last modified November 25, 2026 Perl 5.44
Perl programs often need to run other programs: a shell command, a converter
or a worker. Perl has several tools for this. system runs a
command and waits for it, backticks capture its output, open with
a pipe streams data to or from it, exec replaces the current
program, and fork creates a copy of the running process. The
examples in this article use Unix commands such as echo,
sort and sh.
Running a command with system
The system function starts a command, waits until it finishes and
returns its status. The command and each of its arguments are passed as
separate list items.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my $rc = system('echo', 'Hello there from a child process');
say "system returned $rc";
The child process writes directly to the same terminal as the Perl program, so its output appears without any extra work. The return value 0 means that the command succeeded.
$ perl run_system.pl Hello there from a child process system returned 0
Checking the exit status
The value that system returns is also stored in the special
variable $?. It is not simply the exit code of the command. It
packs three different outcomes into one number, and a program has to decode
it.
#!/usr/bin/perl
use warnings;
use v5.34.0;
sub run {
my @cmd = @_;
no warnings 'exec';
system(@cmd);
if ($? == -1) {
return "could not start: $!";
} elsif ($? & 127) {
return "killed by signal " . ($? & 127);
} else {
return "exit code " . ($? >> 8);
}
}
say "true: ", run('true');
say "false: ", run('false');
say "exit 3: ", run('sh', '-c', 'exit 3');
say "kill: ", run('sh', '-c', 'kill -TERM $$');
say "missing: ", run('no-such-command');
When the command could not be started at all, $? is -1 and
$! says why. Otherwise, the low seven bits hold the number of the
signal that killed the command, or 0. The exit code is in the upper eight bits
and is extracted with $? >> 8. Signals are covered in
Perl signals.
Perl warns when it cannot execute a command. The no warnings 'exec'
line turns that warning off inside the subroutine, because the error is
reported in the return value instead.
$ perl exit_status.pl true: exit code 0 false: exit code 1 exit 3: exit code 3 kill: killed by signal 15 missing: could not start: No such file or directory
The shell form and the list form
When system gets a single string that contains shell
metacharacters such as | or ;, Perl passes it to
/bin/sh. This allows pipelines and redirections, but it is
dangerous when the string contains data from outside the program.
#!/usr/bin/perl
use warnings;
use v5.34.0;
system('echo one two three | wc -w');
my $name = 'notes.txt; echo INJECTED';
say "shell form:";
system("echo $name");
say "list form:";
system('echo', $name);
The first call is a small pipeline that counts words. The
$name variable plays the role of a file name supplied by a user.
In the shell form, the semicolon ends the echo command and the
shell runs a second command. This is a command injection. In the list form, no
shell is involved, and the whole value reaches echo as a single
argument.
$ perl shell_form.pl 3 shell form: notes.txt INJECTED list form: notes.txt; echo INJECTED
Capturing output with backticks and qx
system lets the command print to the terminal. To use the output
in the program, run the command in backticks or with the equivalent
qx operator. Both take a single command string, which is handled
like the single-string form of system.
#!/usr/bin/perl use warnings; use v5.34.0; my $kernel = `uname -s`; chomp $kernel; say "kernel: $kernel"; my @words = qx(printf 'red\\ngreen\\nblue\\n'); chomp @words; say "words: @words"; my $err = `ls /no/such/dir 2>&1`; say "exit code: ", $? >> 8; print "message: $err";
In scalar context, the whole output comes back as one string, including the
trailing newline. In list context, each line is one element. Backticks capture
only standard output. The 2>&1 redirection sends standard
error to the same place, so the error message of ls is captured
too. The exit status is in $?, just as after
system.
$ perl capture.pl kernel: Linux words: red green blue exit code: 2 message: ls: cannot access '/no/such/dir': No such file or directory
Reading from a command with open
Backticks collect the whole output in memory before the program sees any of
it. Opening a command with the -| mode instead gives a filehandle
that delivers the output line by line, while the command runs.
#!/usr/bin/perl
use warnings;
use v5.34.0;
open my $fh, '-|', 'seq', '1', '100'
or die "cannot run seq: $!";
my $sum = 0;
my $count = 0;
while (my $line = <$fh>) {
$sum += $line;
$count++;
}
close $fh or die "seq failed with status $?";
say "read $count numbers, sum $sum";
The list form of open runs seq directly, without a
shell. The program reads the numbers like lines of a file and adds them up.
For a pipe, close waits for the command to finish and sets
$?. It returns false when the command failed, so a failure is
detected at close, not at open.
$ perl read_pipe.pl read 100 numbers, sum 5050
Writing to a command with open
The |- mode works the other way round. Everything the program
prints to the handle becomes the standard input of the command.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @fruits = qw(cherry apple banana apple cherry apple);
open my $fh, '|-', 'sort | uniq -c'
or die "cannot start pipeline: $!";
for my $fruit (@fruits) {
print {$fh} "$fruit\n";
}
close $fh or die "pipeline failed with status $?";
say "done";
Here the command is a single string with a pipe, so it runs through the shell.
The sort | uniq -c pipeline counts how many times each fruit
occurs. It can print its result only after it has read all input, which
happens when close ends the input. That is why the counts appear
before done.
$ perl write_pipe.pl
3 apple
1 banana
2 cherry
done
The environment of a child process
A child process inherits the environment variables of its parent. In Perl,
they are in the %ENV hash. Changing the hash changes the
environment of every command started afterwards.
#!/usr/bin/perl
use warnings;
use v5.34.0;
$ENV{APP_MODE} = 'testing';
system('sh', '-c', 'echo "child sees APP_MODE=$APP_MODE"');
{
local $ENV{APP_MODE} = 'production';
local $ENV{APP_USER} = 'lucia';
system('sh', '-c', 'echo "child sees $APP_MODE for $APP_USER"');
}
system('sh', '-c', 'echo "child sees ${APP_USER:-no user}"');
The first command sees the value assigned to APP_MODE. Inside the
block, local changes one variable and adds another only for the
duration of the block. After the block, APP_USER is gone again,
so the shell falls back to its default value.
$ perl child_env.pl child sees APP_MODE=testing child sees production for lucia child sees no user
Replacing the program with exec
exec takes the same arguments as system, but it does
not start a new process. It replaces the running Perl program with the
command. If it succeeds, it never returns.
#!/usr/bin/perl
use warnings;
use v5.34.0;
say "perl process $$ starts";
exec('sh', '-c', 'echo "shell process $$ replaces it"')
or die "exec failed: $!";
Both lines print the same process ID, which shows that the shell runs in the
process that used to be Perl. The or die part runs only when the
command cannot be executed. exec is mostly used in wrapper
scripts and, as shown below, together with fork.
$ perl exec_cmd.pl perl process 166237 starts shell process 166237 replaces it
Creating child processes with fork
fork duplicates the running program. It returns the child's
process ID in the parent, 0 in the child and undef on failure.
After the split, each process has its own copy of all variables. The parent
collects a finished child with waitpid.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my @pids;
for my $n (1 .. 3) {
my $pid = fork();
die "fork failed: $!" unless defined $pid;
if ($pid == 0) {
exit($n * 10);
}
push @pids, $pid;
}
for my $pid (@pids) {
waitpid($pid, 0);
say "child exit: ", $? >> 8;
}
Each child exits immediately with a different code, and the parent reads the
codes back in the order in which it started the children. Without
waitpid, a finished child stays in the process table as a zombie
until the parent itself exits.
$ perl fork_workers.pl child exit: 10 child exit: 20 child exit: 30
Running commands in parallel
system runs one command at a time. Combining fork
with exec starts several commands that run at the same time. The
parent then waits for them in the order in which they finish.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my %jobs = (
slow => 'sleep 3; exit 0',
fast => 'sleep 1; exit 0',
broken => 'sleep 2; exit 4',
);
my %name_of;
for my $name (sort keys %jobs) {
my $pid = fork();
die "fork failed: $!" unless defined $pid;
if ($pid == 0) {
exec('sh', '-c', $jobs{$name}) or die "exec failed: $!";
}
$name_of{$pid} = $name;
}
while ((my $pid = wait()) != -1) {
say "$name_of{$pid} finished with exit code ", $? >> 8;
}
For every job, the parent forks a child, and the child replaces itself with a
shell that runs the job. The %name_of hash maps process IDs back
to job names. The wait function blocks until any child finishes
and returns its process ID, or -1 when no children are left. The jobs finish
in order of their duration, and the whole program takes about three seconds
instead of six.
For a fixed-size pool of workers, see Perl Parallel::ForkManager.
$ perl parallel.pl fast finished with exit code 0 broken finished with exit code 4 slow finished with exit code 0
Best practices
Keep these points in mind when working with external processes.
- Use the list form:
system('cmd', $arg)andopenwith several arguments avoid the shell and command injection. - Check every status: test the return value of
systemandclose, and decode$?. - Stream large output: read a pipe line by line rather than capturing a huge output into one string.
- Always reap children: call
waitorwaitpidfor every forked process to avoid zombies. - Check exec: follow
execwithor die, especially in a forked child.
Source
perlipc · system · exec · fork · qx
In this article we have run commands with system, decoded the exit
status, compared the shell and list forms, captured output with backticks,
streamed data through pipes, set the environment of a child, replaced the
program with exec and started processes with fork.
See also Perl signals and
Perl Parallel::ForkManager.
Author
List all Perl tutorials.