On Tue, 26 May 1998, Chairul Halim wrote:
> Hello Linux Programmer,
>
> I would like to develop daemon applications for part of my final project.
> So that I need to have any source code relate to daemon programming.
> Could anybody let me know how to find the source code ?
>
> Thanks for your help.
>
> c-halim
Shamelessly pasted from the comp.unix.programmer faq:
Here's the steps to become a daemon.
(1) fork() so the parent can exit, this returns control to the command line
or shell invoking your program. This step is required so that the new
process is guaranteed not to be a process group leader. The next step,
setsid() fails if you're a process group leader.
(2) setsid() to become a process group and session group leader. Since a
controlling terminal is associated with a session, and this new session
has not yet acquired a controlling terminal our process now has no
controlling terminal, (a good thing.)
(3) fork() again so the parent, (the session group leader,) can exit. This
means that we, as a non-session group leader, can never regain a
controlling terminal.
(4) chdir("/") to ensure that our process doesn't keep any directory in use.
Failure to do this could make it so that an administrator couldn't unmount
a slice, because it was our current directory.
(5) umask(0) so that we have complete control over the permissions of anything
we write. We don't know what umask we may have inherited.
(6) close() fds 0, 1, and 2. This releases the standard in, out, and error we
inherited from our parent process. We have no way of knowing where these
fds might have been redirected to. Note that many daemons use sysconf() to
determine the limit _SC_OPEN_MAX. _SC_OPEN_MAX tells you the maximun open
files/process. Then in a loop, the daemon can close all possible file
descriptors. You have to decide if you need to do this or not. If you
think that there might be file-descriptors open you should close them,
since there's a limit on number of concurrent file descriptors.
See NOTE below.
(7) Create a new stdout, an example might be: open("/dev/console",O_RDWR).
(8) dup2() twice to duplicate the fd for standard out for standard in and
standard error.
NOTE: If you're started from inetd some of this is a little different, you
don't have to do the first fork, and fds 0, 1, and 2 are set up to be
the connected socket. That means you should probably skip steps 6, 7
and 8.
* [EMAIL PROTECTED] - Power to the penguin!