Last active
October 29, 2015 15:47
-
-
Save zahna/34fa18c40acb4d5692fc to your computer and use it in GitHub Desktop.
daemonizing in shell (to help me remember)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # my quick and dirty method: | |
| setsid /bin/sh -c "cd /; $@ 2>&1 < /dev/null | logger -t $1 &" | |
| # or the full proper method, found online: | |
| # full daemonization of external command with setsid | |
| daemonize() { | |
| ( # 1. fork | |
| # 2.1. redirect stdin/stdout/stderr before setsid. redirect tty fds to /dev/null. | |
| [[ -t 0 ]] && exec < /dev/null | |
| [[ -t 1 ]] && exec > /dev/null | |
| [[ -t 2 ]] && exec 2> /dev/null | |
| # 3. ensure cwd isn't a mounted fs | |
| cd / | |
| # 4. umask (leave this to caller) | |
| # umask 0 | |
| # 5. close unneeded fds. close all non-std* fds. | |
| eval exec {3..255}\>\&- | |
| # 6. run command | |
| exec setsid "$@" | |
| ) & | |
| } | |
| # daemonize without setsid, keeps the child in the jobs table | |
| daemonize-job() { | |
| ( # 1. fork | |
| # 2.1. redirect stdin/stdout/stderr before setsid. redirect tty fds to /dev/null. | |
| [[ -t 0 ]] && exec </dev/null | |
| [[ -t 1 ]] && exec >/dev/null | |
| [[ -t 2 ]] && exec 2>/dev/null | |
| # 2.2.2. guard against HUP and INT (in child) | |
| trap '' 1 2 # 2.2.2. guard against HUP and INT (in child) | |
| # 3. ensure cwd isn't a mounted fs | |
| cd / | |
| # 4. umask (leave this to caller) | |
| # umask 0 | |
| # 5. close unneeded fds. close all non-std* fds. | |
| eval exec {3..255}\>\&- | |
| # 6. run job | |
| if [[ $(type -t "$1") != file ]]; then | |
| "$@" | |
| else | |
| exec "$@" | |
| fi | |
| ) & | |
| # 2.2.3. guard against HUP (in parent) | |
| disown -h $! | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment