tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: How to properly daemonize?



Others have ansered your questions, but I wanted to address this one.

>-- what's the point of some daemons assuring the outer process doesn't exit
>   before the innermost actually runs?

So, I had to write something recently where I wanted the daemon to exit
with an error code and print a useful error message out if startup
failed (it was easy to get the environment it wanted wrong).  But the
obvious solution of initializing in the parent and then calling fork()
wasn't an option because the libraries I was using officially said that
using the library in a child across a fork() was undefined behavior.
So, the solution I came up with was:

- Call fork() in parent, and then use sigwait() to wait for SIGCHLD or SIGUSR1
- In the child, perform library initialization. If it fails, print out
  the error message on stderr and exit.  If it succeeds send a SIGUSR1 to
  the parent and then perform the rest of the daemonization steps as discussed
  previously.
- If the parent gets a SIGCHLD, call waitpid() and exit with the exit code
  that the child exited with. If the parent gets a SIGUSR1, then exit normally.

--Ken


Home | Main Index | Thread Index | Old Index