# #=============================================================================== # # FILE: Daemon.pm # # DESCRIPTION: A separate package for Daemonizing the program. # # FILES: --- # BUGS: --- # NOTES: --- # AUTHOR: (), <> # COMPANY: # VERSION: 1.0 # CREATED: 10/22/08 19:35:52 IST # REVISION: --- #=============================================================================== package Daemon; use strict; use warnings; use POSIX; use Carp; #If we export functions then there is no need for us to use Packagename::funtion_name. We can just use the function. # Object Creation sub new { bless {}, shift } ; # To open maximum file descriptors. sub Open_Descriptors { my $openmax = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );#This will give the maximum open descriptors. (!defined($openmax) || $openmax < 0) ? 1024 : $openmax;#If that is given then take that else use 1024. } #This is used to fork and exit to get rid of the controlling terminal. sub Forking { my $pid; if (($pid = fork()) < 0) { die("can't fork"); } elsif ($pid != 0) { exit(0); } return ; } #=== FUNCTION ================================================================ # NAME: Daemonize # PURPOSE: To make daemon process. # PARAMETERS: ???? # RETURNS: ???? # DESCRIPTION: ???? # THROWS: no exceptions # COMMENTS: none # SEE ALSO: n/a #=============================================================================== sub Daemonize { my $class = shift; my ( $fd0,$fd1,$fd2,$pid ); umask(0); # Clear the file creation mask. #Fork the process. $class->Forking; croak "Cannot detach from controlling terminal" unless my $sess_id = POSIX::setsid(); $SIG{'HUP'} = 'IGNORE'; $class->Forking;#Again call the fork. ## Change working directory to root. #chdir "/"; # Close all the file descriptors foreach my $i (0 .. $class->Open_Descriptors) { POSIX::close($i); } ## Reopen stderr, stdout, stdin to /dev/null open(STDIN, "+>/dev/null"); open(STDOUT, "+>&STDIN"); open(STDERR, "+>&STDIN"); return ; } 1;