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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access