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

Hello, I'm trying to write a daemon which will restart itself when it receives SIGHUP. Whenever I send the signal, the daemon never seems to start a new one using the system call (I get a return code of 512 - what does that mean?). I'm using the following code:
#!/usr/local/bin/perl -w use Proc::Daemon; use strict; my $root = "/temp"; my $time_to_die = 0; sub signal_handler { $time_to_die = 1; } sub phoenix { my $me = "$root/minidaemon.pl"; logMessage("I'm about to refork by running '$me'!"); my $ret = system($me); if ($ret) { logMessage("Should have run system($me), but which returned $r +et: $?, carrying on"); } else { exit(0); } } sub logMessage { my $message = shift; local $| = 1; open(FILE_HANDLE, ">>$root/daemon.out") or die("log file open fail +ed: $!"); print FILE_HANDLE "$$ : $message\n" ; close(FILE_HANDLE); } Proc::Daemon::Init; $SIG{INT} = $SIG{TERM} = \&signal_handler; $SIG{HUP} = \&phoenix; while (!$time_to_die) { sleep(1); logMessage("hello"); } logMessage("died");
I know I am probably missing something very obvious, but this initiate hasn't got a scooby. Thanks in advance!

Replies are listed 'Best First'.
Re: Restarting a daemon
by chromatic (Archbishop) on Jan 22, 2004 at 18:57 UTC

    You might want a fork/exec pair instead of the system call, which will wait until the launched process exits before returning.

    I always have to look up what to do with $? after a system call, but I think perldoc -f system explains that you need to shift it right eight bits or so to find the real error number. In this case, it may be that the system call doesn't know what to do with a Perl program. It may not be marked executable or it may not be where you think it is.

    I'd probably use $0 instead of hard-coding a path, but there may be security concerns there.

Re: Restarting a daemon
by Abigail-II (Bishop) on Jan 22, 2004 at 19:29 UTC
    By doing a system(), you say "start this process, wait till it finishes". What you want is an exec of yourself. Something like:
    exec $0 => @ARGV; die "exec failed: $!";

    Abigail

Re: Restarting a daemon
by revdiablo (Prior) on Jan 22, 2004 at 19:06 UTC

    As chromatic mentioned, if you check out perldoc -f system you'll see the following interesting little tidbit:

    You can check all the failure possibilities by inspecting $? like this +: if ($? == -1) { print "failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n", $? >> 8; }

    Perhaps the extra verbosity in this error reporting will help you narrow down the problem.