Daemonize a process in shell?

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.

Tags:

Linux

Bash

Daemon