Linux Daemon – How to Daemonize a Process in Shell

bashdaemonlinux

http://linuxg.net/how-to-transform-a-process-into-a-daemon-in-linux-unix/ gives an example of daemonizing a process in bash:

$ nohup firefox& &> /dev/null

If I am corrrect, the command is the same as "nohup and background a process".
But isn't a daemon more than a nohupped and background process?

What steps are missing here to daemonize a process?

For example, isn't changing the parent process necessary when daemonizing a process? If yes, how do you do that in bash? I am still trying to understand a related reply https://unix.stackexchange.com/a/177361/674.

What other steps and conditions?

See my related question https://stackoverflow.com/q/35705451/156458

Best Answer

From the Wikipedia article on daemon:

In a Unix environment, the parent process of a daemon is often, but not always, the init process. A daemon is usually either created by a process forking a child process and then immediately exiting, thus causing init to adopt the child process, or by the init process directly launching the daemon. In addition, a daemon launched by forking and exiting typically must perform other operations, such as dissociating the process from any controlling terminal (tty). Such procedures are often implemented in various convenience routines such as daemon(3) in Unix.

Read the manpage of the daemon function.

Running a background command from a shell that immediately exits results in the process's PPID becoming 1. Easy to test:

# bash -c 'nohup sleep 10000 &>/dev/null & jobs -p %1'
1936
# ps -p 1936
      PID    PPID    PGID     WINPID   TTY         UID    STIME COMMAND
     1936       1    9104       9552  cons0       1009 17:28:12 /usr/bin/sleep

As you can see, the process is owned by PID 1, but still associated with a TTY. If I log out from this login shell, then log in again, and do ps again, the TTY becomes ?.

Read here why it's important to detach from TTY.

Using setsid (part of util-linux):

# bash -c 'cd /; setsid sleep 10000 </dev/null &>/dev/null & jobs -p %1'
9864
# ps -p 9864
      PID    PPID    PGID     WINPID   TTY         UID    STIME COMMAND
     9864       1    9864       6632  ?           1009 17:40:35 /usr/bin/sleep

I think you don't even have to redirect stdin, stdout and stderr.

Related Question