Making a Daemon Server

Problem

You want your program to run as a daemon.

Solution

If you are paranoid and running as root, chroot to a safe directory:

chroot("/var/daemon")
    or die "Couldn't chroot to /var/daemon: $!";

Fork once, and let the parent exit.

$pid = fork;
exit if $pid;
die "Couldn't fork: $!" unless defined($pid);

Dissociate from the controlling terminal that started us and stop being part of whatever process group we had been a member of.

use POSIX;

POSIX::setsid()
    or die "Can't start a new session: $!";

Trap fatal signals, setting a flag to indicate we need to gracefully exit.

$time_to_die = 0;

sub signal_handler {
    $time_to_die = 1;
}

$SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&signal_handler;
# trap or ignore $SIG{PIPE}

Wrap your actual server code in a loop:

until ($time_to_die) {
    # ...
}

Discussion

Before POSIX, every operating system had its own way for a process to tell the operating system “I’m going it alone, please interfere with me as little as possible.” POSIX makes it much cleaner. That said, you can still take advantage of any operating system-specific calls if you want to.

The chroot call is one of those non-POSIX calls. It makes a process change where it thinks the directory / is. For instance, after chroot "/var/daemon", if the process tries to read the file /etc/passwd, it will read /var/daemon/etc/passwd. A chrooted process needs copies of any files it will run made available inside its new /, of course. For instance, our chrooted process would need /var/daemon/bin/csh ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.