- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

20.3.3 Complete Dissociation of Child from Parent

In some cases (starting server processes, for instance) you'll want to completely dissociate the child process from the parent. This is often called daemonization. A well behaved daemon will also chdir() to the root directory (so it doesn't prevent unmounting the filesystem containing the directory from which it was launched) and redirect its standard file descriptors from and to /dev/null (so that random output doesn't wind up on the user's terminal).

use POSIX 'setsid';
sub daemonize {
    chdir '/'               or die "Can't chdir to /: $!";
    open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
    open STDOUT, '>/dev/null'
                            or die "Can't write to /dev/null: $!";
    defined(my $pid = fork) or die "Can't fork: $!";
    exit if $pid;
    die "Can't start a new session: $!" if setsid == -1;
    open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";

The fork() has to come before the setsid() to ensure that you aren't a process group leader (the setsid() will fail if you are). If your system doesn't have the setsid() function, open /dev/tty and use the TIOCNOTTY ioctl() on it instead. See tty(4) for details.

Non-Unix users should check their Your_OS::Process module for other solutions.

ISBN 9781906966027Perl Language Reference ManualSee the print edition