I'm aware some (all?) daemons fork when they're being started. I'm under the impression this is to run the child processes as less privileged users, especially if the daemon is something like a HTTP server.
Why is this necessary though? Couldn't a process start up and drop its privileges without forking a child process? Is it "mandatory" for forking, or is there some other special reason (other than for running multiple child worker processes)?
I'm new to this and would appreciate all the help I can get.
I think daemons fork for several reasons:
One reason is to detach process from any shell that starts it. Some shells (Bash, for instance) kill children upon exit, unless special, shell-specific precautions are made. Forking is a generic way to evade this.
Another reason is to report that the daemon was successfully started.
Assume it doesn't fork. How would you know that the daemon has been started successfully? You can't just read and parse daemon output, because daemon management programs should do it in a generic way. So the only way is to get return code of the program.
Indeed, if a daemon failed to start (for example, it couldn't find config file), you would know that immediately. But hey, if a daemon has been started successfully, it may never return! So your daemon manager can't know whether daemon is still trying to start, or has been started, and is working. Fork would solve the problem, and the forking program would return success if a fork worked well.
As for privileges, dropping them after
execve
is much less secure than doing so beforeexecve
. Here's another reason why fork is handy.To back up what daramarak said, from Wikipedia's article:
Basically the process needs to disassociate from other processes and from terminals and such.
I was under the impression that this was done to keep the daemon completely unattached to any other processes (like a shell or similar). By forking and exiting the parent process the Orphaned process will be "adopted" by the system init process.
Daemons must fork two times because they must be indipendent of other processes, that is there's no way to kill the daemon killing another process, and must be running in the background, that is not attached to a terminal.
On startup the daemon forks and the parent dies. This makes the forked process a child of
init
, so basically it's indipendent from other processes.On the second fork the child is no more a process leader, and is detached from the terminal.
Others good practices may apply, reading the source code of a simple daemon may be insightful.