2011-06-22 42 views
3
停止Perl的守護

我一直工作在一個Perl守護進程Linux和這裏是它的骨骼:啓動和在Linux中

#!/usr/bin/env perl 
use File::Copy; 
use Socket; 
use Sys::Hostname; 
use POSIX qw(setsid); 
use Env; 

use Sys::Info::Constants qw(:device_cpu); 

my $daemonName = 'proc'; 

my $proc; 
my $error; 
my $file = "Proc.pl"; 
my $pidfile = ">/var/run/proc.pid"; 
my $pid2check = "/var/run/proc.pid"; 
my $pid; 


if (!$error) { 
    LogMessage("$daemonName : PID $proc : Begin"); 
} 

if (!$error) { 
    LogMessage("$daemonName : PID $proc : Writing pid information to $pidfile"); 
    print FILE $proc . "\n"; 
    close (FILE); 
} 

$SLEEP_TIME = 5; # seconds 

#Main loop of Daemon 
while (!$error) { 
    sleep($SLEEP_TIME); 

} 


if ($error) { 
    LogMessage("$file : PID $proc : Error $error"); 
} 

LogMessage("$file : PID $proc : END"); 

exit(0); 


sub Daemonize { 

if (!(chdir '/')) { 
    $error .= "Can't chdir to /: $!"; 
} 
if (!(umask 0)) { 
    $error .= "Unable to umask 0"; 
} 

unless (open STDIN, '/dev/null') { 
    $error .= "Can't read /dev/null: $!"; 
} 

open(OLD_OUT,">&STDOUT"); 

#All print statments will now be sent to our log file 
unless (open STDOUT, '>>/var/log/proc.log') { 
    $error .= "Can't read /var/log/proc.log: $!"; 
} 
#All error messages will now be sent to our log file 
unless (open STDERR, '>>/var/log/proc.log') { 
    $error .= "Can't write to /var/log/proc.log: $!"; 
} 

defined($pid = fork); 
#Exit if $pid exists (parent) 

if ($pid) 
{ 
    print OLD_OUT "Service successfully installed.\n"; 
    exit(0); 
} 

#As Child 
setsid(); 
$proc = $$; 
return ($proc); 
} 


#Prints log messages 
sub LogMessage { 
my $message = $_[0]; 
print localtime() . " $message\n"; 
} 

我是比較新的Perl和我不知道會是什麼最簡單的方法來啓動和停止這個守護進程?另外我將如何檢查以確保沒有已經運行的實例?

回答

5

一般來說,daemonisation是用double fork方法完成的。這是常用的習慣用法,有libraries這樣做,你應該考慮使用。通常使用pid或lockfile來確保一次只運行一個實例。

如果您打算將此作爲系統進程使用,也可以使用類似upstartsupervisord的方法來爲您執行進程管理和「只有一個」。