“Daemon-izing” Your Script
Problem
Sometimes you want a script to run as a daemon, i.e., in the background and never ending. To do this properly you need to be able to detach your script from its controlling tty, that is from the terminal session used to start the daemon. Simply putting an ampersand on the command isn’t enough. If you start your daemon script on a remote system via an SSH (or similar) session, you’ll notice that when you log out, the SSH session doesn’t end and your window is hung until that script ends (which, being a daemon, it won’t).
Solution
Use the following to invoke your script, run it in the background, and still allow yourself to log out:
nohup mydaemonscript 0<&-1>/dev/null 2>&1 &
or:
nohup mydaemonscript >>/var/log/myadmin.log 2>&1 <&- &
Discussion
You need to close the controlling tty, which is connected in three ways to your (or any) job: standard input (STDIN), standard output (STDOUT), and standard error (STDERR). We can close STDOUT and STDERR by pointing them at another file— typically either a log file, so that you can retrieve their output at a later time, or at the file /dev/null to throw away all their output. We use the redirecting operator > to do this.
But what about STDIN? The cleanest way to deal with STDIN is to
close the file descriptor. The bash syntax to do
that is like a redirect, but with a dash for the file-name (0<&- or <&-).
We use the nohup command so that the script is run without being interrupted by a hangup signal when we log off. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access