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

I'm following the recipe shown in http://perldoc.perl.org/perlipc.html#Handling-the-SIGHUP-Signal-in-Daemons to make my daemon process restart itself. It works fine on the first restart, but after that kill -1 pid seems to be ignored: print statements in the $SIG{HUP} subroutine aren't executed. However, other signals continue to get through to their respective handlers.

The problem even occurs in the sample program shown in the perlipc documentation.

It's such simple concept - I would have thought the exec() would pretty thoroughly clean the slate. Any idea why the HUP signal handler wouldn't "take" the second time?

Replies are listed 'Best First'.
Re: Using SIGHUP to restart a daemon
by McA (Priest) on Oct 16, 2013 at 23:30 UTC
      Thanks - here's a link to the solution: http://www.perlmonks.org/?node_id=440924 although as I noted in the thread, the author seems to have sometimes written SIGINT where he meant to write SIGHUP. If you copy the code and make that correction in two places, it works correctly.
Re: Using SIGHUP to restart a daemon
by vsespb (Chaplain) on Oct 17, 2013 at 17:51 UTC
    Reported it as bug in documentation: RT#120256
Re: Using SIGHUP to restart a daemon
by vsespb (Chaplain) on Oct 17, 2013 at 09:19 UTC
    Hack small proof-of-concept code which reproduce your problem, and post here, so other can test it.
      If you follow the link in the original post, it takes you to perlipc doc containing code that illustrates the problem.
        Looks like it's known problem in perl.
        Also, similar issue Can't catch signals after an exec?

        Code can be simplified to
        $sub = sub { exec "perl $0" }; $SIG{INT} = $sub; $SIG{USR1} = $sub; while(1) { print ++$counter, "\n"; sleep 1; }
        (if you press Ctrl-C, it restarts only once)
        Workaround for example in perldoc:
        #!/usr/bin/env perl use POSIX (); use FindBin (); use File::Basename (); use File::Spec::Functions; $| = 1; # make the daemon cross-platform, so exec always calls the script # itself with the right path, no matter how the script was invoked +. print STDERR "STARTED\n"; my $script = File::Basename::basename($0); my $SELF = catfile($FindBin::Bin, $script); # POSIX unmasks the sigprocmask properly my $need_restart = 0; $SIG{HUP} = sub { print "got SIGHUP\n"; $need_restart = 1; }; code(); sub code { print "PID: $$\n"; print "ARGV: @ARGV\n"; my $count = 0; while (++$count) { sleep 2; if ($need_restart) { exec($SELF, @ARGV) || die "$0: couldn't restart: $!"; } print "$count\n"; } }

        (i.e. need to call exec() outside of signal handler)

        And another workaround is posted above by McA Re: Using SIGHUP to restart a daemon