tech-userlevel archive

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

How to properly daemonize?



I know about daemon(3). I'm aware this question is not NetBSD-specific. 
However, I want to be able to write portable code. Plus there's so much 
nonsense around on the subject that I want to make sure I'm understanding 
things correctly in the end.

Steps to daemonize:

-- You want to get orphaned and reparented to init (or poetterd or whatever). 
That's simple: fork and let the parent exit. However, what's the exact reason 
for wanting to get reparented to init? Is it just to be sure someone will be 
wait()ing for you or are there other reasons, too?

-- You want to get rid of your control tty (so you don't accidently recieve 
signals, or is there more to it?). You do that by calling setsid. Since that 
may fail if you are a process group leader, you do it after the fork.

-- You now are a session leader but don't want to accidently acquire a new 
control tty in case some user-defined input leads to opening a tty. POSIX 
says that this is implementation-dependent. Is it SYSV doing that? So you 
fork again to not be session leader.

-- You chdir to / to free any mount points.

-- Most programs close std{in,out} and re-open them from /dev/null. Is that 
only to make sure not to block a mount point or is it required to detatch 
from the control tty?
Some prograns open one fd on /dev/null and dup2() it to 0/1. I guess this is 
just an optimization?
Which flags to re-open(2) std{in,out,err} with? I had supposed O_RDONLY 
for in and O_WRONLY for out/err, but I've seen O_RDONLY for both stdin and 
stdout as well as O_RDWR for stderr. 

-- Some programs go into great lengths (communicating over a pipe or 
catching/sending SIGHUP) to assure that the original process doesn't 
terminate before the child/grandchild is running. Is this just to ensure 
the daemon is actually operational before the command returns or is it 
required to avoid some races I don't think of?

-- Is there a (portable) way to detach from the controlling tty in a shell 
script?


Home | Main Index | Thread Index | Old Index