This takes care of all basic daemonization. It uses an optional argument for STDOUT and STDERR, or /dev/null otherwise. Emancipates your process from it's shell. Behaves as a good citizen. requires POSIX. Mostly cut/paste from the manual pages.
sub daemonize { require POSIX; my $logfile = shift; $logfile = '/dev/null' unless defined $logfile; chdir '/' or die "Can't chdir to /: $!"; open STDIN, '/dev/null' or die "failed opening STDIN: $!"; open STDOUT, ">>$logfile" or die "failed opening logfile $logfile: + $!"; { defined(my $pid = fork) or die "Can't fork: $!"; exit if $pid; } POSIX::setsid() or die "Can't start a new session: $!"; open STDERR, '>&STDOUT' or die "Can't dup STDOUT for STDERR: $!"; return 1; }

Replies are listed 'Best First'.
Re: Yet Another Daemonization Stub
by Zaxo (Archbishop) on Nov 15, 2004 at 03:46 UTC

    Some problems with this, easily repaired.

    1. You leave the partition your starting directory is on undismountable. chdir to system root, '/'.
    2. Svr4 systems require a second fork, to assure your daemon never gets a controlling terminal.
    3. With a double fork, it may be advisable to sleep (with select undef, undef, undef, .01) until the parent doesn't answer kill, so that the first child has no chance of going zombie.
    4. You don't close any other open file handles.

    After Compline,
    Zaxo

    A reply falls below the community's threshold of quality. You may see it by logging in.