17.15. Making a Daemon ServerProblemYou want your program to run as a daemon. Solution
If you are paranoid and running as root, 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) { # ... } DiscussionBefore 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
The operating system expects a child's parent to wait when the child dies. Our daemon process has no particular parent to do this, so we need to disinherit it. This we do by
Now we're almost ready to begin. We don't want signals like SIGINT to kill us immediately (its default behavior), so we use
The signal SIGPIPE is a special case. It's easy to get (by writing to a filehandle whose other end is closed) and has unforgiving default behavior (it terminates your process). You probably want to either ignore it ( See Also
Your system's
setsid
(2) and
chroot
(1) manpage (if you have them);
the |
|