I am writing a shell script that I would like to run as a daemon on startup without using external tools like daemontools or daemonize.
Linux Daemon Writing HOWTO
According to the Linux Daemon Writing HOWTO, a proper daemon has the following characteristics:
- forks from the parent process
- closes all file descriptors (i.e.,
stdin
,stdout
,stderr
) - opens logs for writing (if configured)
- changes the working directory to one that is persistent (usually
/
) - resets the file mode mask (umask)
- creates an unique Session ID (SID)
daemonize Introduction
The daemonize Introduction goes further, stating that a typical daemon also:
- disassociates from its control terminal (if there is one) and ignores all terminal signals
- disassociates from its process group
- handles
SIGCLD
How would I do all this in a sh
, dash
, or bash
script with common Linux tools only?
The script should be able to run on as many distros as possible without additional software, although Debian is our primary focus.
NOTE: I know there are plenty of answers on the StackExchange network recommending the use of nohup
or setsid
, but neither of these methods tackles all of the requirements above.
EDIT: The daemon(7) manpage also gives some pointers, although there seem to be some differences between older-style SysV
daemons and newer systemd
ones. Since compatibility with a variety of distros is important, please ensure the answer makes clear any differences.
daemon
and those other things are for running arbitrary shell scripts with no provision for running as a daemon. Since you're the author, fully in control of how that script is written, make it so it can just be launched from a systemd unitfile or rc.d script. You did specify "Proper"!