James wrote:
> how do i write a daemon? I know what they are (little programs that do something
> useful in the background), but are they just normal programs that get pushed
> into the background?
Basically, yes.
> how do i make one (e.g foobar) and have it so that it runs in the background
> if you type 'foobar -D' (or something).
> I have a feeling it has something to do with fork() but how? For a fork() to
> work you need a parent process and a child don't you?
No. fork() creates the child process.
To create a daemon, you would basically:
1. Call fork(). The parent process then exits, leaving the child
running in the background.
2. Call setsid() to establish a new session and process group.
3. Call `chdir("/")'.
4. Call umask(0), so that file modes aren't affected by any inherited
umask setting.
5. Close all open file descriptors.
Also, you should specify O_NOCTTY when opening anything which might be
a terminal device, so that the process doesn't inadvertantly acquire a
controlling TTY.
> and how do i monitor a /dev/TTYS? device so that when my modem picks up
> the line and connects to a remote computer my daemon does something, then
> when the modem puts down the line the daemon does something else?
This is difficult to do in a portable manner. You could try using the
TIOCMGET ioctl() to monitor the status lines; that may be adequate.
Alternatively, you could try polling for a lock file.
--
Glynn Clements <[EMAIL PROTECTED]>