Daemon::Simple - Perl extension for making script as daemon with start|stop controlling on unix system


Daemon-Simple documentation Contained in the Daemon-Simple distribution.

Index


Code Index:

NAME

Top

Daemon::Simple - Perl extension for making script as daemon with start|stop controlling on unix system

SYNOPSIS

Top

  use Daemon::Simple;

  Daemon::Simple::init($command);

  or

  Daemon::Simple::init($command,"~/");

  or

  my $homedir = `pwd`; chomp($homedir);
  my $pidfile = "/var/run/ffencoder.pid";
  my $command = $ARGV[0];
  Daemon::Simple::init($command,$homedir,$pidfile);

  ## Daemon script ##
  open(FILE,">out.txt");
  select(FILE);




  sleep(10);
  close(FILE);
  __END__

  # in shell
  $ perl foo.pl start
  $ perl foo.pl stop

DESCRIPTION

Top

This module is good for making a script as a daemon. A daemon script has start|stop controlling command. It is simple by adding Daemon::Simple::init() on first line of script.

This module is implemented by wrapping Proc::Daemon.

EXPORT

None by default.

SEE ALSO

Top

Proc::Daemon

Proc::ProcessTable

AUTHOR

Top

HyeonSeung Kim, <sng2nara@hanmail.net>

COPYRIGHT AND LICENSE

Top


Daemon-Simple documentation Contained in the Daemon-Simple distribution.

package Daemon::Simple;

use 5.008001;
use strict;
use warnings;

our $VERSION = '0.03';

# Preloaded methods go here.

require Proc::ProcessTable;
require File::Spec;
# Daemon init
sub init
{
	my ($command,$homedir,$pidfile) = @_;
	unless($command)
	{
		print "$0 {start|stop}\n";
		exit;
	}
	unless($homedir)
	{
		$homedir = File::Spec->curdir();
	}
	unless($pidfile)
	{
		$pidfile = $homedir."/$0.pid";
	}
	my $pid = get_pidfile($pidfile);
	my $is_running = is_running($pid); 
	if( $command eq 'start' )
	{
		if( $is_running )
		{
			print "$0 is Already running.\n";
			exit; # stop here
		}
		else
		{
			# run
			print "$0 is Starting.\n";
		}
	}
	elsif( $command eq 'stop' )
	{
		if( $is_running )
		{
			print "Sending stop-signal to $0 (PID:$pid).\n";
			kill_process($pid);
			while( is_running($pid) )
			{
				sleep(1);
			}
			print "$0 (PID:$pid) is stopped.\n";
			destroy_pidfile($pidfile);
		}
		else
		{
			print "$0 (PID:$pid) is Already stopped.\n";
		}
		exit; # stop here
	}
	
	use Proc::Daemon;
	Proc::Daemon::Init;
	create_pidfile($pidfile);
	chdir($homedir);
}

sub is_running
{
	my $pid = shift;
    my $table = Proc::ProcessTable->new()->table;
	my %processes = map { $_->pid => $_ } @$table;
	return exists $processes{$pid};
}

sub get_pidfile
{
	my $pidfile = shift;
	#get pid from file
	return 0 unless( -e$pidfile );
	open(FILE, "$pidfile");
	my $pid = <FILE>;
	chomp($pid);
	close(FILE);
	return $pid;
}

sub create_pidfile
{
	my $pidfile = shift;
	#write pid to file
	open(FILE,">$pidfile");
	print FILE $$;
	close(FILE);
}

sub kill_process
{
	my $pid = shift;
	#kill process
	kill(9,$pid);
}
sub destroy_pidfile
{
	my $pidfile = shift;
	#delete pid file
	unlink($pidfile);
}