Meridius has asked for the wisdom of the Perl Monks concerning the following question:

While handling TERM signal, I am trying to set a flag and also ignoring the TERM signal. But sleep breaks if the TERM signal is issued to this process.
$SIG{TERM} = sub {$SIG{TERM}="IGNORE"; $term_sig = 1;}; print "\n $$ \n"; sleep(20); print "TERM signal ignored\n";
Code to issue TERM signal
kill -15 <pid>
Please help me in understanding why the sleep breaks even though TERM is handled.

Replies are listed 'Best First'.
Re: Handling TERM signal
by ikegami (Patriarch) on Mar 09, 2007 at 06:05 UTC

    You can either either ignore a signal instance or handle it, but not both. Only future signals will be affected by your $SIG{TERM} = "IGNORE".

    use Time::HiRes qw( sleep ); # Optional. print("Process Id = $$\n"); print("Start time = " . localtime() . "\n"); my $term_sig; local $SIG{TERM} = sub { $SIG{TERM} = "IGNORE"; $term_sig = 1; }; # Sleep for 20 seconds. Ignore interruptions. my $sleep_til = time() + 20; for (;;) { my $sleep_len = $sleep_til - time(); last if $sleep_len <= 0; sleep($sleep_len); } print("End time = " . localtime() . "\n"); if ($term_sig) { print "Received TERM signal\n" } else { print "Did not receive TERM signal\n" }

    Tested:

    $ 603944.pl Process Id = 65138 Start time = Fri Mar 9 01:06:18 2007 End time = Fri Mar 9 01:06:38 2007 Did not receive TERM signal $ 603944.pl Process Id = 65236 Start time = Fri Mar 9 01:07:00 2007 $ kill -s TERM 65236 End time = Fri Mar 9 01:07:20 2007 Received TERM signal
Re: Handling TERM signal
by jesuashok (Curate) on Mar 09, 2007 at 10:19 UTC
    why the sleep breaks even though TERM is handled.
    you are handling a TERM signal for the whole perl program. You have not written any specific code to handle a TERM signal, while sleep function is in progress.

    Signal handling is a general concepts with regard to the OS you are working on. To learn more about what is signal, signal handling and so on, you can refer UnixSignals. If you want to learn more still google helps you out.