daemonfork

Why do daemons fork?


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.


Solution

  • I think daemons fork for several reasons:

    1. 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.

    2. 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.

    3. As for privileges, dropping them after execve is much less secure than doing so before execve. Here's another reason why fork is handy.