Monday, December 20, 2021

Usage of alarm signal handler '$SIG{ALRM}' in Perl

In the following example we can see the usage of alarm signal handler '$SIG{ALRM}' in Perl. 

$SIG{ALRM} is used to execute definite lines of code on regular time intervals, in a program's normal course of execution. Here we shall display "Hello World" text after every 30 seconds.

Here the following Program name is 'test_alarm.pl'

#!/usr/bin/perl

## setup alarm signal handler to execute timely
our $alarm_interval = 30; # 30 secs

$SIG{ALRM} = sub {
	print "Hello World\n";
	alarm($alarm_interval);
};

alarm($alarm_interval);

### Infinite loop to test out running of alarm
while (1) {
}


Steps To Run The Program:
-------------------------
1) On the command prompt goto the directory where the program is created, type the following and hit enter.

perl test_alarm.pl

Output of the above program is either of the following lines:

Hello World
Hello World
Hello World