Preventing ^C stopping / killing a program - Perl
Archive - Originally posted on "The Horse's Mouth" - 2008-12-05 08:14:35 - Graham EllisHere's a demonstration - in Perl - that shows you how to avoid a ^C (Control C) dropping you straight out of a program.
Have you ever accidentally hit ^C in the wrong window and terminated a long-running process just before it finished ... well, by setting $SIG{INT} to the address of a sub you want to run, you can divert the signal in Perl. The example code here simulates a long running process with a loop of 60 short sleeps (naps?) ...
$SIG{"INT"} = \&nowayjose;
$| = 1;
for (1..60){
print "dot";
sleep 1;
if ($rq) {
exit if (time() - $recent < 4) ;
print "\nNah\n";
$rq = 0;
$recent = time();
}
}
sub nowayjose {
$rq = 1;
}
You'll note that all my extra "sub" does is set a flag so that the interrupt can be nicely handled at the end of the loop, that the handler turns the interrupt flag back off, and that I've written the program so that a second ^C within 4 seconds WILL cause it to exit.
As an afterthought ... if you disable ^C completely (i.e. if you don't use the 4 second trick), how will you get out of the program? Well ... you'll still be able to suspend it with ^Z then kill it with kill %1, or you'll be able to find its process id and use a kill -9