Signals in Perl

Here’s the translation of the Go signals example to Perl, formatted in Markdown suitable for Hugo:

Our program demonstrates how to handle Unix signals in Perl. For example, we might want a server to gracefully shutdown when it receives a SIGTERM, or a command-line tool to stop processing input if it receives a SIGINT. Here’s how to handle signals in Perl.

#!/usr/bin/env perl

use strict;
use warnings;
use sigtrap qw(handler signal_handler INT TERM);

# This subroutine will be called when a signal is received
sub signal_handler {
    my $signal = shift;
    print "\n";
    print "$signal received\n";
    exit;
}

print "awaiting signal\n";

# The program will wait here until it receives a signal
while (1) {
    sleep 1;
}

print "exiting\n";

Perl’s signal handling works by setting up signal handlers. We use the sigtrap module to register our signal_handler subroutine to handle SIGINT and SIGTERM signals.

The signal_handler subroutine is defined to print the received signal and then exit the program.

In the main part of the script, we print a message indicating that we’re waiting for a signal, and then enter an infinite loop. This loop will continue until a signal is received and handled.

When we run this program it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C) we can send a SIGINT signal, causing the program to print INT received and then exit.

$ perl signals.pl
awaiting signal
^C
INT received

In Perl, we don’t need to explicitly create channels or goroutines for signal handling. The signal handling is managed by the Perl interpreter and our registered signal handler is called when a signal is received.

This example demonstrates a simple way to handle signals in Perl, allowing for graceful shutdown or other appropriate actions when specific signals are received.