“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.

In the first example, we use the file descriptor numbers (i.e., 0, 1, 2) explicitly in all three redirections. They are optional in the case of STDIN and STDOUT, so in our second example we don’t use them explicitly. We also put the input redirect at the end of the second command rather than at the beginning, since the order here is not important. (However, the order is important and the file descriptor numbers are necessary in redirecting STDERR.)

See Also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.246