Unix Daemons in Perl | 2 | WebReference

Unix Daemons in Perl | 2

Unix Daemons in Perl

Daemon Rules

There are several rules or characteristics that most daemons possess. If a daemon does not follow these basic rules, it will most likely become a demon and wreak havoc on your system.

Fork and Exit

The first thing a daemon should do is fork() a child process and have the parent process exit(). This is necessary for several reasons. First, it disassociates the process from the controlling terminal, or the login shell. Second, it removes the process from the process group that initiated the program. This ensures that the process is not a process group leader, which is required for setsid() to run successfully.

Call setsid()

setsid() is a POSIX function that turns the process into a session leader, group leader, and ensures that it doesn't have a controlling terminal.

Change Working directory

The current working directory should be changed with chdir to the root directory (/). This is necessary to avoid using a working directory that resides on a mounted partition. If the process is started on a mounted partition, the system administrator wouldn't be able to unmount the partition until the process was halted. You could, of course, specify a different working directory as long as it doesn't reside on a remotely mounted partition.

File Creation Mode

The umask determines the default permissions new files are assigned. Setting umask to 0 removes the defaults that might otherwise disable permissions the daemon intended to enable when creating files.

Close Unneeded File Handles

Besides closing any filehandles that might have been opened, daemons often redirect STDIN to read from, and STDOUT and STDERR to write to /dev/null.

open STDIN,  '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>/dev/null';
open STDERR, '>/dev/null';

Logging Messages

In some cases, you may want to record an error or messages to a log file on the system. This can be accomplished by redirecting STDOUT and STDERR to one or more log files.

open STDOUT, ">>$access_log" or die "Can't write to $access_log: $!";
open STDERR, ">>$error_log" or die "Can't write to $error_log: $!";

http://www.internet.com

Produced by Jonathan Eisenzopf
All Rights Reserved. Legal Notices.
Created: December 28, 1999
Revised: January 21, 2000

URL: http://www.webreference.com/perl/tutorial/9/2.html