http://www.perlmonks.org?node_id=986290

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

I am forking a child process (a perl file is called in that child process) and in that child there is a Signal Handling Routine written. I want that when I send a signal to this child (SIG USR1), it should exit giving return code 110. This is my Code:
$SIG{USR1} = 'HANDLER'; sub HANDLER { print "Got 'USR1'. Exiting with Return Code '110' !!\n"; exit 110; }
But with this it exits from Handler with 110 and not from the child. Is there anything I am doing wrong here?

Replies are listed 'Best First'.
Re: Signal Handling in a Child Process
by aitap (Curate) on Aug 08, 2012 at 14:56 UTC
    Perhaps you need to use local there?
    $ perl -E' if (my $pid = fork) { say "My pid is $$, child is $pid"; local $SIG{USR1} = sub { say "parent"; exit 0 }; sleep 1 while 1 } else { local $SIG{USR1} = sub { say "child"; exit 0 }; sleep 1 while 1 }' & [1] 19681 My pid is 19681, child is 19683 $ kill -USR1 19683 child $ kill -USR1 19681 parent [1]+ Done perl -E'if (my $pid = fork) { say "My pi +d is $$, child is $pid"; local $SIG{USR1} = sub { say "parent"; exit +0 }; sleep 1 while 1 } else { local $SIG{USR1} = sub { say "child"; e +xit 0 }; sleep 1 while 1}
    Or have I misunderstood something?
    Sorry if my advice was wrong.
Re: Signal Handling in a Child Process
by Illuminatus (Curate) on Aug 08, 2012 at 17:29 UTC
    I am forking a child process (a perl file is called in that child process)...
    I'm not sure what you mean here. Do you mean that you are forking a child that is, in turn, forking a perl script?. When I run the following:
    #! /usr/bin/perl sub HANDLER { print "Got 'USR1'. Exiting with Return Code '110' !!\n"; exit 110; } $SIG{USR1} = 'HANDLER'; while (1) { sleep(60); }
    In background, and send SIGUSR1 to it, it immediately exits with code 110 (if only the HANDLER function had returned, the script would have continued to run).

    fnord