Hi, all monks:
I recently write a daemon script, which can relaunch itself when it received the HUP signal, what the weird part is that it only can relaunch itself when it received the HUP signal at the first time, but can't relaunch itself at the other times, seems that it didn't execute the HUP signal handler, but just ignore the HUP signal. The following is my simple daemon script:
#!/usr/bin/perl
use strict;
use warnings;
use FindBin;
use POSIX qw( setsid );
my $runDir = "$FindBin::Bin";
my $pidFile = "$FindBin::Bin/hup.pid";
my $exeFile = $0;
$SIG{HUP} = \&doSigHup;
$SIG{__DIE__} = \&logDie;
$SIG{__WARN__} = \&logWarn;
# get process status
if ( -e $pidFile ) {
open( PIDFILE, $pidFile ) or die "[EMERG] $!\n";
my $pid = <PIDFILE>;
close PIDFILE;
die "[EMERG] process is still running\n" if kill 0 => $pid;
die "[EMERG] can't remove pid file\n"
unless -w $pidFile && unlink $pidFile;
}
# go into daemon
open( my $pidFH, ">", $pidFile ) or die "[EMERG] $!\n";
my $parentPid = daemon();
print $pidFH $parentPid;
close $pidFH;
hupMain();
sub hupMain {
while (1) {
warn "Running hup main function.\n";
sleep 3;
}
}
sub logDie {
my $errLog = "$FindBin::Bin/hup.err";
my $time = scalar localtime;
open( my $errFH, ">>", $errLog );
print $errFH $time, " ", @_;
close $errFH;
die @_;
}
sub logWarn {
my $errLog = "$FindBin::Bin/hup.err";
my $time = scalar localtime;
open( my $errFH, ">>", $errLog );
print $errFH $time, " ", @_;
close $errFH;
}
sub doSigHup {
warn "[INFO] received SIGHUP,prepare to reload...\n";
relaunch( $runDir, $pidFile, $exeFile );
die "[EMERG] reload failed\n";
}
sub relaunch {
my ( $rundir, $pidFile, $exeFile ) = @_;
warn "[EMERG] rundir should not be undef" and return unless $run
+dir;
warn "[EMERG] pidfile should not be undef" and return unless $pid
+File;
warn "[EMERG] exefile should not be undef" and return unless $exe
+File;
chdir $rundir;
unlink $pidFile;
exec "$exeFile";
}
sub daemon {
my $child = fork();
die "[EMERG] can't fork\n" unless defined $child;
exit 0 if $child;
setsid();
open( STDIN, "</dev/null" );
open( STDOUT, ">/dev/null" );
open( STDERR, ">&STDOUT" );
chdir $runDir;
umask(022);
$ENV{PATH} = '/bin:/usr/bin:/sbin:/usr/sbin';
return $$;
} ## end sub daemon
I test the relaunch function part:
[monitor@august-dev tmp]$ ./hup.pl
[monitor@august-dev tmp]$ cat hup.pid
15393[monitor@august-dev tmp]$ kill -HUP 15393
[monitor@august-dev tmp]$ cat hup.pid
15395[monitor@august-dev tmp]$ kill -hup 15395
[monitor@august-dev tmp]$ cat hup.pid
15395[monitor@august-dev tmp]$ kill -hup 15395
[monitor@august-dev tmp]$ cat hup.pid
15395[monitor@august-dev tmp]$
It shows that, the first I 'kill -HUP 15393', the daemon relaunch itself, and the pid changes to 15395, but the second time I 'kill -HUP 15395', the daemon remains the same pid 15395, and didn't relaunch itself. the third time I 'kill -HUP 15395' got the same result.
Can anyone give some tips why the daemon can't relaunch itself at the second time ?