Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signal handling in perl

Tags:

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?

like image 348
shivams Avatar asked Nov 20 '25 06:11

shivams


1 Answers

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";
}
like image 109
choroba Avatar answered Nov 23 '25 07:11

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!