« Contributor to XML Standard: "XML is Too Hard for Programmers" | Main | David Weiss Spent a Week with a Treo 300 »

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:"

  1. Change the working directory to the root directory ( / ).
  2. Set standard input, output, and error to /dev/null (unless you want to enable logging).
  3. Fork a new process and test to make sure it worked.
  4. Call setsid from the Posix module.
  5. Set the umask.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


CTDATA Venutures (CTDATA) develops Internet and Intranet applications for corporations and non profit organizations. Our services include:

  • Consulting services for Movable Type and TypePad-based publishing systems (visit our Weblog Improvement website for more information),
  • Financial services business process consulting,
  • Content management system and knowledge management system consulting,
  • Apache web server engineering and hosting,
  • MySQL, Sybase, and Microsoft SQL Server architecture and development,
  • SOAP, REST, and XML-RPC system architecture and programming, including Amazon Web Services and
  • Weblog publishing.
For more information, contact Dave Aiello by email at dave [at] daveaiello.com or call him at +1-267-352-4420.
Copyright © 1995-2010, CTDATA Ventures. All Rights Reserved.
Powered by
Movable Type 4.25