![]()
|
SysAdmin Topics
|
Table of Contents by Ross Moffatt, October 2009 OverviewI suppose this article is about the trap command. Mainly to highlight its usefulness as opposed to using the nohup command, cron commad, at command, or other ways to have a script picked up by the init process as a parent. I also show the usefulness of trapping the SIGTERM, 15, signal and running commands just before a script exits. #!/bin/bash # MyShellScript i=0 Leaving scripts running when you logoffThe standard way to run a script in the background is to use the & character at the end of the command line, like this. $ ./myShellScript & When you run a script, its Parent Process ID (PPID) is your shell's Process ID (PID). This can be seen by looking at the process list. $ ps -ef | grep MyShellScript This shows the user "ross" is the process owner, the PID is 1300, and the PPID is 1281. Use kill <PID> to stop the script running, for example, in my case: $ kill 1300 To have the script "picked up" by the init process on logout, trap the SIGHUP, 1, signal by adding a trap command to the script. #!/bin/bash # MyShellScript trap "" 1 i=0 Now run the script, log off, and log back in again. Doing a process list shows MyShellScript still running, with a PPID of 1, owned by init. When you log off, the session may seem to hang and you may need to disconnect the session depending upon the terminal emulation program you are using.
# ps -ef | grep MyShellScript So now the PPID is 1, which is the init process, as can be seen as follows. $ ps -ef|grep init OK, so now the only way to stop this process from running is to use the kill <pid> command, for example, in my case: $ kill 1421 Exiting nicely when a script is sent a SIGTERM signalBy default, a signal SIGTERM, 15, is sent; so let's trap it. #!/bin/bash # MyShellScript MyMessage="I don\'t want to stop" trap "" 1 i=0 So let's run this script, and send it a kill SIGTERM signal. $ ./MyShellScript & $ kill 1674 Checking the process list shows our script still running, and lets set it a SIGKILL signal. $ ps -ef|grep MyShellScript $ kill -9 1674 Now lets exit nicely after receiving the SIGTERM signal. So here is the modified MyShellScript. #!/bin/bash MyMessage="Stopping" trap "" 1 i=0 Now let's run this script and send it a SIGTERM signal. $ ./MyShellScript & Stopping [1]+ Done ./MyShellScript A number of commands can be run upon receiving the SIGTERM trap, such as writing log messages, deleting temporary files, etc. List of signalsBy using the kill command, a list of signals can be obtained. $ kill -l Conclusion
About The AuthorRoss Moffatt has been a UNIX System Administrator for more than 10 years, and can be contacted at ross.stuff@telstra.com. |