#!/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 = ; 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 $rundir; warn "[EMERG] pidfile should not be undef" and return unless $pidFile; warn "[EMERG] exefile should not be undef" and return unless $exeFile; 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( STDERR, ">&STDOUT" ); chdir $runDir; umask(022); $ENV{PATH} = '/bin:/usr/bin:/sbin:/usr/sbin'; return $$; } ## end sub daemon #### [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]$