in reply to daemon with Perl on Linux

I recently had to write a daemon. Due to corporate policies, I was unable to use non-core modules. The shell of the daemon is actually not very complex though...
use POSIX qw{ setsid getcwd close sysconf _SC_OPEN_MAX }; ... foreach my $i (0 .. openmax()) { POSIX::close($i); } open(STDIN, "+>/dev/null"); open(STDOUT, "+>&STDIN"); open(STDERR, "+>&STDIN"); # ignore these signals for (qw(TSTP TTIN TTOU PIPE POLL STOP CONT CHLD)) { $SIG{$_} = 'IGNORE' if (exists $SIG{$_}); } # handle these signals for (qw(INT HUP ABRT QUIT TRAP TERM)) { $SIG{$_} = 'interrupt' if (exists $SIG{$_}); } unless (my $pid = fork()) { exit if $pid; POSIX::setsid; # set session id chdir '/'; # change to root directory umask 0; # clear the file creation mask while(1) { # do whatever your daemon needs to do ... } } sub interrupt { # do whatever to gracefully shutdown ... die "$0 terminated successfully.\n"; }
Hope this is useful to you. As always, any suggestions are welcome. --Akoya

Replies are listed 'Best First'.
Re^2: daemon with Perl on Linux
by rimvydazas (Novice) on Nov 28, 2007 at 21:09 UTC
    I found a couple of scripts similar to this one. As far as I understand, this script will do check ups on "whatever daemon needs to" check on. But what if my daemon needs to listen to the socket, but not to do any kind of check ups? Can I somehow to implement that? It might sound dumb to you, but I am newbie... :]