-
-
Save henfiber/d610dda34f21e9499e888e3d49be68aa to your computer and use it in GitHub Desktop.
daemonize sh function
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
_daemonize() | |
{ #daemonize an external command | |
#http://blog.n01se.net/blog-n01se-net-p-145.html | |
[ -z "${1}" ] && return 1 | |
( # 1. fork, to guarantee the child is not a process | |
# group leader, necessary for setsid) and have the | |
# parent exit (to allow control to return to the shell) | |
# 2. redirect stdin/stdout/stderr before running child | |
[ -t 0 ] && exec </dev/null | |
[ -t 1 ] && exec >/dev/null | |
[ -t 2 ] && exec 2>/dev/null | |
if ! command -v "setsid" >/dev/null 2>&1; then | |
# 2.1 guard against HUP and INT (in child) | |
trap '' 1 2 | |
fi | |
# 3. ensure cwd isn't a mounted fs so it does't block | |
# umount invocations | |
cd / | |
# 4. umask (leave this to caller) | |
# umask 0 | |
# 5. close unneeded fds | |
#XCU 2.7 Redirection says: open files are represented by | |
#decimal numbers starting with zero. The largest possible | |
#value is implementation-defined; however, all | |
#implementations shall support at least 0 to 9, inclusive, | |
#for use by #the application. | |
i=3; while [ "${i}" -le "9" ]; do | |
eval "exec ${i}>&-" | |
i="$(($i + 1))" | |
done | |
# 6. create new session, so the child has no | |
# controlling terminal, this prevents the child from | |
# accesing a terminal (using /dev/tty) and getting | |
# signals from the controlling terminal (e.g. HUP, INT) | |
if command -v "setsid" >/dev/null 2>&1; then | |
exec setsid "$@" | |
else | |
if [ ! -f "${1}" ]; then | |
"$@" | |
else | |
exec "$@" | |
fi | |
fi | |
) & | |
# 2.2 guard against HUP (in parent) | |
if ! command -v "setsid" >/dev/null 2>&1; then | |
disown -h "${!}" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment