Using Perl to Write a UNIX Daemon
Dave Aiello wrote, "Earlier today, I converted a Perl program I wrote to a UNIX daemon. I did this because the program, which had been run as a cron job, was failing more and more frequently. It's easy to get a cron-based program to fail if it has to be run frequently-- the execution time of an instance of the program simply has to exceed the time between invocations of the job."
"A better approach is to daemonize the program. In other words, put an outer loop in the program that causes it to execute repeatedly, with a programmatic delay at the end of the loop. As long as variables are re-initialized properly and resources are conserved, the program will theoretically run forever."
"I know that any self-respecting professional Perl programmer would look at PerlMonks for help before looking anywhere else. But, I decided to perform a Google search first. As a result of this choice, I was able to find a great tutorial on WebReference called UNIX Daemons in Perl."
"This is a great tutorial-- well worth reading-- despite the fact that it was originally written in December 1999. It provides a very simple example that can be used as a model for modification of existing Perl programs."
"It's surprising that the daemonization of a Perl program is largely done in 10 lines of code. But, the psedo-code for daemonization is this simple:"
- Change the working directory to the root directory ( / ).
- Set standard input, output, and error to /dev/null (unless you want to enable logging).
- Fork a new process and test to make sure it worked.
- Call setsid from the Posix module.
- Set the umask.