##---------------------------------------------------------------------------## ## File: ## @(#) Daemon.pm 1.3 97/12/16 16:30:39 @(#) ## Author: ## Earl Hood ehood@medusa.acs.uci.edu ## Synopsis: ## use Daemon; ## $sess_id = Daemon::init; ## ## ## ... your code here ... ## ## Description: ## This module contains the routine "Init" which ## can be called by a perl program to initialize itself as a ## daemon. The routine achieves this by the following: ## ## 1. Forks a child and exits the parent process. ## 2. Becomes a seesion leader (which detaches the program from ## the controlling terminal). ## 3. Changes the current working directory to "/". ## 4. Clears the file creation mask. ## ## The calling program is responible for closing unnecessary open ## file handles. ## ## The return value is the session id returned from setsid(). ## ## If an error occurs in Init so it cannot perform the above ## steps, than it calls "die" with an error message. One can ## prevent program termination by using "eval" to capture any ## error messages. ##---------------------------------------------------------------------------## ## Copyright (C) 1997 Earl Hood, ehood@medusa.acs.uci.edu ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of either: ## ## a) the GNU General Public License as published by the Free ## Software Foundation; either version 2, or (at your option) ## later version, or ## ## b) the "Artistic License" which comes with Perl. ##---------------------------------------------------------------------------## package Daemon; use Exporter (); @ISA = qw( Exporter ); @EXPORT = (); @EXPORT_OK = (); $VERSION = "0.0.1.3"; ##---------------------------------------------------------------------------## use POSIX; ##---------------------------------------------------------------------------## sub init { my($pid, $sess_id); ## Fork and exit parent ## FORK: { if ($pid = fork) { ## parent process exit 0; } elsif (defined $pid) { ## child process last FORK; } elsif ($! =~ /No more process/) { sleep 5; redo FORK; } else { die "Can't fork: $!\n"; } } ## Detach ourselves from the terminal ## die "Cannot detach from controlling terminal\n" unless $sess_id = POSIX::setsid(); chdir "/"; ## Change working directory umask 0; ## Clear file creation mask $sess_id; } ##---------------------------------------------------------------------------## 1;