shivams
shivams

Reputation: 2727

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?

Upvotes: 3

Views: 2610

Answers (2)

elcaro
elcaro

Reputation: 2317

Rather than duplicating the handler for each SIG, it's neater to use sigtrap.

This example prevents the user from killing, but you can do whatever you want in the handler. Of course, if your handler does an 'exit' you also have the END sub to do additional stuff as well.

use strict;
use warnings;
use sigtrap 'handler' => \&sig_handler, qw(INT TERM KILL QUIT);

sub sig_handler {
   my $sig_name = shift;
   print "You can't kill me! $sig_name caught";
}

for (1 .. 10) {
    print $_ . "\n";
    sleep 1;
}

Alternatively you can use the existing signal lists...

use sigtrap 'handler' => \&sig_handler, qw(any normal-signals error-signals stack-trace);

see perldoc sigtrap for more info

Upvotes: 5

choroba
choroba

Reputation: 242333

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";
}

Upvotes: 5

Related Questions