Details for writing daemons differ between Unices (including Linux) and WinNT/Win2000/WinXP.
Lincoln Stein covers the basics for Unix in Chapter 10, Forking Servers and the inetd Daemon, and Chapter 14, Bulletproofing Servers, in Network Programming with Perl.
There's a bit more to being a well-behaved daemon than is obvious at first glance.
On page 312, Stein notes that a well-behaved daemon should:
- "Autobackground" itself (fork/parent-exit), then close file handles and lose any assocition with a controlling terminal.
- Change the current working directory to a known directory.
- Change the file creation mask to a known state.
- Set the PATH to a known state.
- Record its process ID in a known place
- Optionally use syslog to write diagnostics
- Optionally handle HUP signals (e.g. to reload configuration files)
- Options use chroot()
He then spends the better part of a chapter fleshing that out and giving examples.