shivams shivams - 4 months ago 14
Perl Question

Signal handling in perl

use strict;
use warnings;

print "hello\n";
sleep(10);
print "print before alarm\n";
alarm 5;

$SIG{'ALRM'} = \&alarm;
$SIG{'INT'} = \&alarm;
$SIG{'TERM'} = \&alarm;

sub alarm {
print "alarm signal hanndled\n";
}


I am not able to handle signals either for alarm or for pressing ctrl+c. I searched and find this as a way to do signal handling. What am i doing wrong?

Answer

First, set the handlers. Then, set the alarm. Last, do the time-consuming operation (sleep). You have it upside down:

#! /usr/bin/perl
use strict;
use warnings;

$SIG{'ALRM'} = \&alarm;
$SIG{'INT'}  = \&alarm;
$SIG{'TERM'} = \&alarm;

print "hello\n";
alarm 5;
sleep(10);
print "after sleep\n";

sub alarm {
   print "alarm signal handled\n";
}
Comments