ZetCode

Perl signals

last modified November 25, 2026 Perl 5.44

A signal is a short notification that the operating system delivers to a process. The terminal sends INT when the user presses Ctrl-C, service managers send TERM to ask a program to shut down, and a timer set with alarm sends ALRM when it expires. Each signal has a default action, usually terminating the process. A program can replace it with its own handler.

Perl exposes signals through the special %SIG hash. The keys are signal names without the SIG prefix, such as INT or TERM, and the values say what to do when the signal arrives. This article covers signals on Unix-like systems. Windows supports only a small subset of them.

Signal names and numbers

Every signal has a name and a number. The numbers differ between operating systems, so code should use the names. The core Config module lists the signals that the current Perl knows about.

signal_names.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Config;

my @names = split ' ', $Config{sig_name};
my @nums  = split ' ', $Config{sig_num};

for my $i (1 .. 15) {
    printf "%2d %s\n", $nums[$i], $names[$i];
}

$Config{sig_name} and $Config{sig_num} are space-separated strings with matching positions. The first entry is the dummy signal ZERO with number 0, so the loop starts at index 1. The shell command kill -l prints a similar list.

$ perl signal_names.pl
 1 HUP
 2 INT
 3 QUIT
 4 ILL
 5 TRAP
 6 ABRT
 7 BUS
 8 FPE
 9 KILL
10 USR1
11 SEGV
12 USR2
13 PIPE
14 ALRM
15 TERM

A first handler

A handler is a code reference stored in %SIG. Perl calls it with the signal name as the only argument. In the example, the program sends a signal to itself so that we do not have to press any keys.

first_handler.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

$SIG{INT} = sub {
    my ($name) = @_;
    say "caught $name";
};

kill 'INT', $$;
say "the program continues";

The kill function sends a signal. Its first argument is the signal name and the rest are process IDs. The special variable $$ holds the ID of the current process. Without the handler, INT would terminate the program before the last line. With the handler, Perl runs the subroutine and then continues where it left off.

$ perl first_handler.pl
caught INT
the program continues

Stopping a loop gracefully

Long-running programs, such as workers and daemons, should finish the current task and clean up when they are asked to stop. The usual pattern is a handler that only records the signal in a variable. The main loop checks the variable and decides when to quit.

worker.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $stop_sig;

$SIG{INT}  = sub { $stop_sig = shift };
$SIG{TERM} = sub { $stop_sig = shift };

my $n = 0;

until ($stop_sig) {
    $n++;
    say "working on task $n";
    sleep 1;
}

say "received $stop_sig after $n tasks";
say "cleaning up";

Both INT and TERM store their name in $stop_sig. The handlers do no other work, so they cannot leave the program in a half-finished state. The until loop ends at the next check, and the program reports what it did before it exits.

Perl delivers signals safely. When a signal arrives, Perl notes it and runs the handler between two operations, never in the middle of one. A blocking call such as sleep is interrupted and returns early. That is why the program reacts to Ctrl-C at once instead of after the full second.

$ perl worker.pl
working on task 1
working on task 2
working on task 3
working on task 4
^Creceived INT after 4 tasks
cleaning up

Ignoring and restoring signals

Besides a code reference, a %SIG entry can hold one of two strings. 'IGNORE' discards the signal and 'DEFAULT' restores the operating system's default action. With local, a change lasts only until the end of the enclosing block.

ignore_signal.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

{
    local $SIG{INT} = 'IGNORE';
    kill 'INT', $$;
    say "INT ignored inside the block";
}

say "default action restored";
kill 'INT', $$;
say "this line is never printed";

Inside the block, the INT signal is ignored and the program goes on. When the block ends, local puts back the previous value, which is the default action. The second INT therefore terminates the program and the last line never runs.

A process killed by a signal has no ordinary exit code. The shell reports 128 plus the signal number instead, which is 130 for INT.

$ perl ignore_signal.pl
INT ignored inside the block
default action restored
$ echo $?
130

Timeouts with alarm

The alarm function starts a timer in whole seconds. When the timer expires, the process receives ALRM. Combined with die and eval, it puts a time limit on an operation that could otherwise block forever, such as a network read.

timeout.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $ok = eval {
    local $SIG{ALRM} = sub { die "timed out\n" };
    alarm 2;
    sleep 5;
    alarm 0;
    1;
};
alarm 0;

if ($ok) {
    say "the operation finished";
} else {
    print "error: $@";
}

The sleep 5 stands in for a slow operation. After two seconds the ALRM handler dies, which leaves the eval block immediately. The eval returns false and $@ holds the message. The die and eval pair is described in Perl error handling.

alarm 0 cancels a pending timer. It appears twice: inside the block for the case when the operation finishes in time, and after the block for the case when the operation dies for some other reason. Without the second call, a forgotten timer could fire later in unrelated code. The handler is set with local inside the eval, so it is removed when the block ends.

$ perl timeout.pl
error: timed out

A reusable timeout helper

The timeout pattern has several parts that are easy to get wrong, so it belongs in a subroutine. The next program wraps it in with_timeout and also uses fractional seconds. The core Time::HiRes module provides versions of alarm and sleep that accept them.

with_timeout.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Time::HiRes qw(alarm sleep);

sub with_timeout {
    my ($secs, $code) = @_;

    my $ok = eval {
        local $SIG{ALRM} = sub { die "timed out after $secs s\n" };
        alarm $secs;
        $code->();
        alarm 0;
        1;
    };
    alarm 0;

    return $ok ? "done" : "failed: $@";
}

for my $delay (0.2, 0.4, 0.8) {
    my $res = with_timeout(0.5, sub { sleep $delay });
    chomp $res;
    say "task of $delay s: $res";
}

with_timeout takes a limit and a code reference. It returns done when the code finishes in time, otherwise the error message. Importing alarm and sleep from Time::HiRes replaces the built-in functions, which work only with whole seconds. The first two tasks finish within half a second. The third one is cut off.

$ perl with_timeout.pl
task of 0.2 s: done
task of 0.4 s: done
task of 0.8 s: failed: timed out after 0.5 s

Signalling a child process

Signals are also a way for processes to talk to each other. In the next program, a parent process starts a child with fork and later tells it to stop with TERM. The fork and waitpid functions are covered in Perl processes.

signal_child.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $pid = fork();
die "fork failed: $!" unless defined $pid;

if ($pid == 0) {
    my $running = 1;
    $SIG{TERM} = sub { $running = 0 };

    sleep 1 while $running;

    say "child: got TERM, exiting";
    exit 3;
}

sleep 1;
say "child alive: ", kill(0, $pid) ? "yes" : "no";

kill 'TERM', $pid;
waitpid($pid, 0);
say "child exit code: ", $? >> 8;

say "child alive: ", kill(0, $pid) ? "yes" : "no";

The child installs a TERM handler and waits in a loop, like the worker above. The parent sends TERM and waits for the child with waitpid. The exit code is in the high byte of $?.

Signal number 0 is special. kill 0, $pid sends nothing and only checks whether the process exists and whether we may signal it. The function returns the number of processes it reached, so a true value means the process is alive. After waitpid, the child is gone.

$ perl signal_child.pl
child alive: yes
child: got TERM, exiting
child exit code: 3
child alive: no

Detecting death by a signal

Not every signal can be handled. KILL and STOP cannot be caught or ignored. A process killed with KILL ends at once, without running any cleanup code. The parent can still find out what happened from the status in $?.

kill_status.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use Config;

my @names = split ' ', $Config{sig_name};

my $pid = fork();
die "fork failed: $!" unless defined $pid;

if ($pid == 0) {
    sleep 10;
    exit 0;
}

kill 'KILL', $pid;
waitpid($pid, 0);

my $sig = $? & 127;
say "child killed by signal $sig ($names[$sig])" if $sig;

The low seven bits of $? hold the number of the signal that killed the child, or 0 when the child exited normally. The program uses the Config list from the first section to turn the number back into a name.

$ perl kill_status.pl
child killed by signal 9 (KILL)

Blocking signals

Sometimes a piece of code must not be interrupted, for example while it updates several related files. Instead of ignoring signals, which would lose them, a program can block them. A blocked signal is kept pending and is delivered when the block is lifted.

block_signals.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use POSIX qw(sigprocmask SIG_BLOCK SIG_UNBLOCK SIGINT);

$SIG{INT} = sub { say "handler: caught INT" };

my $set = POSIX::SigSet->new(SIGINT);

sigprocmask(SIG_BLOCK, $set) or die "cannot block INT: $!";
say "critical section starts";
kill 'INT', $$;
say "critical section ends";

sigprocmask(SIG_UNBLOCK, $set) or die "cannot unblock INT: $!";
say "INT unblocked";

The POSIX module provides sigprocmask, which changes the set of blocked signals. A POSIX::SigSet object holds the signals to block or unblock. The INT sent inside the critical section waits, and the handler runs right after SIG_UNBLOCK.

$ perl block_signals.pl
critical section starts
critical section ends
handler: caught INT
INT unblocked

Best practices

These recommendations help to write signal handling code that is safe and predictable.

Source

perlipc: Signals · perlvar: %SIG · kill · alarm · Time::HiRes · POSIX

In this article we have handled signals with %SIG, stopped a loop gracefully, set timeouts with alarm, signalled a child process with kill and blocked signals with sigprocmask. See also Perl processes, Perl error handling and Perl Parallel::ForkManager.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.