1754324 Members
2585 Online
108813 Solutions
New Discussion юеВ

perl daemon script

 
SOLVED
Go to solution
Inesa Clinko
Advisor

perl daemon script

Plese help me with Perl daemon script.
When I'm executing the main script, it created child process,but don't want to exit itself. :(
I have to press enter, in oder to stop the main script. I want to use this script in
/sbin/init.d, so I want the main script to exit itself, and the child process to remain as daemon, doing some job...
Here is the script bellow:

#!/usr/bin/perl -w

use POSIX;
use Getopt::Std;
use English;
use strict;

use constant FALSE => 0;
use constant TRUE => 1;

# ****** Main Program

my $kontinue = TRUE;

sub close_n_exit
{
$kontinue = FALSE;
return(15);
} # close_n_exit

my $cc = 0;
my $pid = fork();
if ($pid == 0)
{ # child - daemonize the process

POSIX::setsid() or die "Can't start a new session: $!";
$SIG{HUP} = 'IGNORE';
# $SIG{QUIT} = 'IGNORE';
$SIG{INT} = 'IGNORE';
$SIG{PIPE} = 'IGNORE';
$SIG{TERM} = \&close_n_exit;
while ($kontinue)
{
print `date`;
sleep(10);
}
}
else
{ # parent process - just exit; the child is doing the real work
exit($cc);
}
exit($cc);


Please help me to make the right script.
It will be points, of course :)
2 REPLIES 2
James R. Ferguson
Acclaimed Contributor
Solution

Re: perl daemon script

Hi:

Run this version. Notice that the child process directs its STDOUT to a file (which you can view with 'tail -f' as the daemon runs on).

Your code is decidedly C-like. A much more Perl-ish version is this:

#!/usr/bin/perl
use POSIX qw( setsid );
use strict;
use warnings;
my $logfile = '/var/tmp/mydaemon';
my $pid;
sub close_n_exit {
print STDERR "going away...\n";
exit 1;
} # close_n_exit
chdir '/' or die "Can't cd to /: $!\n";
open( STDIN , '<', '/dev/null' ) or die "Can't open /dev/null: $!\n";
open( STDOUT, '>', $logfile ) or die "Can't open '$logfile': $!\n";
$|++; #...set autoflush on STDOUT...
defined($pid = fork) or die "Can't fork(): $!\n";
exit if $pid;
setsid or die "Can't start a new session: $!";
$SIG{HUP} = 'IGNORE';
$SIG{QUIT} = 'IGNORE';
$SIG{INT} = 'IGNORE';
$SIG{PIPE} = 'IGNORE';
$SIG{TERM} = \&close_n_exit;
while (1) {
print STDOUT scalar localtime, "\n";
sleep 10;
}
exit 0

Regards!

...JRF...
Inesa Clinko
Advisor

Re: perl daemon script

Thanks ,James