Skip to content

Instantly share code, notes, and snippets.

@javier-lopez
Created October 15, 2015 07:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save javier-lopez/d6cd37d568b5f2655280 to your computer and use it in GitHub Desktop.
Save javier-lopez/d6cd37d568b5f2655280 to your computer and use it in GitHub Desktop.
daemonize sh function
_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