9.8. Trapping Signals

While your program is running, if you press Control-C or Control-, your program terminates as soon as the signal arrives. There are times when you would rather not have the program terminate immediately after the signal arrives. You could arrange to ignore the signal and keep running or perform some sort of cleanup operation before actually exiting the script. The trap command allows you to control the way a program behaves when it receives a signal.

A signal is defined as an asynchronous message that consists of a number that can be sent from one process to another, or by the operating system to a process if certain keys are pressed or if something exceptional happens.[6]The trap command tells the shell to terminate the command currently in execution upon the receipt of a signal. If the trap command is followed by commands within quotes, the command string will be executed upon receipt of a specified signal. The shell reads the command string twice, once when the trap is set, and again when the signal arrives. If the command string is surrounded by double quotes, all variable and command substitution will be performed when the trap is set the first time. If single quotes enclose the command string, variable and command substitution do not take place until the signal is detected and the trap is executed.

[6] Bolsky, Morris I. And Korn, David G. The New KornSheel Command And Programming, 2nd ed. Prentice Hall. 1995.p.327.

Use the command kill -l or trap -l to get a list of all signals. Table 9.6 on page 460 provides a list of signal numbers and their corresponding names.

Format

trap 'command; command' signal-number
trap 'command; command' signal-name

Example 9.61.
					trap 'rm tmp*; exit 1'  0 1 2 15
trap 'rm tmp*; exit 1'  EXIT HUP INT TERM

Explanation

When any of the signals 1 (hangup), 2 (interrupt), or 15 (software termination) arrives, remove all the tmp files and exit.

If an interrupt comes in while the script is running, the trap command lets you handle the interrupt signal in several ways. You can let the signal behave normally (default), ignore the signal, or create a handler function to be called when the signal arrives.

Signal names such as HUP and INT are normally prefixed with SIG, for example, SIGHUP, SIGINT, and so forth.[7] The bash shell allows you to use symbolic names for the signals, which are the signal names without the SIG prefix, or you can use the numeric value for the signal. See Table 9.6. A pseudo signal name EXIT, or the number 0, will cause the trap to be executed when the shell exits.

[7] SIGKILL, number 9, often called a "sure kill," is not trapable.

Table 9.6. Signal Numbers and Signals (kill -l)
1) SIGHUP9) SIGKILL18) SIGCONT26) SIGVTALRM
2) SIGINT10) SIGUSR119) SIGSTOP27) SIGPROF
3) SIGQUIT11) SIGSEGV20) SIGTSTP28) SIGWINCH
4) SIGILL12) SIGUSR221) SIGTTIN29) SIGIO
5) SIGTRAP13) SIGPIPE22) SIGTTOU30) SIGPWR
6) SIGABRT14) SIGALRM23) SIGURG 
7) SIGBUS15) SIGTERM24) SIGXCPU 
8) SIGFPE17) SIGCHLD25) SIGXFSZ 

Resetting Signals

To reset a signal to its default behavior, the trap command is followed by the signal name or number. Traps set in functions are recognized by the shell that invoked the function, once the function has been called. Any traps set outside the function are also recognized with the function.

Example 9.62.
						trap 2
						or
						 trap INT
					

Explanation

Resets the default action for signal 2, SIGINT. The default action is to kill the process when the interrupt key (Control-C) is pressed.

Ignoring Signals.

If the trap command is followed by a pair of empty quotes, the signals listed will be ignored by the process.

Example 9.63.
						trap " " 1 2
						or
						trap "" HUP INT
					

Explanation

Signals 1 (SIGHUP) and 2 (SIGINT) will be ignored by the shell process.

Listing Traps

To list all traps and the commands assigned to them, type trap.

Example 9.64.
(At the command line)
1  $ trap 'echo "Caught ya!; exit"' 2
2  $ trap
   trap -- 'echo "Caught ya!; exit 1"' SIGINT
3  ..$trap -
					

Explanation

  1. The trap command is set to exit on signal 2 (Control-C).

  2. The trap command without an argument lists all set traps.

  3. If the argument is a dash, all signals are reset to their original values, whatever they were when the shell started up.

Example 9.65.
(The Script)
   #!/bin/bash
   # Scriptname: trapping
   # Script to illustrate the trap command and signals
   # Can use the signal numbers or bash abbreviations seen
   # below. Cannot use SIGINT, SIGQUIT, etc.
1  trap 'echo "Control–C will not terminate $0."'  INT
2  trap 'echo "Control– will not terminate $0."'   QUIT
3  trap 'echo "Control–Z will no stop $0."'        TSTP
4  echo  "Enter any string after the prompt.
   When you are ready to exit, type "stop"."
5  while true
   do
6        echo –n "Go ahead…> "
7        read
8        if [[ $REPLY == [Ss]top ]]
         then 
9             break
         fi
10 done
(The Output)
   $ trapping
4  Enter any string after the prompt.
						When you are ready to exit, type "stop". 
6  Go ahead…> this is it^C
1  Control–C will not terminate trapping.
6  Go ahead…> this is it again^Z
3  Control–Z will not terminate trapping.
6  Go ahead…> this is never it|^
2  Control– will not terminate trapping.
6  Go ahead…> stop 
   $

Explanation

  1. The first trap catches the INT signal, Control-C. If Control-C is pressed while the program is running, the command enclosed in quotes will be executed. Instead of aborting, the program will print Control-C will not terminate trapping and continue to prompt the user for input.

  2. The second trap command will be executed when the user presses Control-, the QUIT signal. The string Control- will not terminate trapping will be displayed and the program will continue to run. This signal, SIGQUIT by default, kills the process and produces a core file.

  3. The third trap command will be executed when the user presses Control-Z, the TSTP signal. The string Control-Z will not terminate trapping will be displayed, and the program will continue to run. This signal normally causes the program to be suspended in the background if job control is implemented.

  4. The user is prompted for input.

  5. The while loop is entered.

  6. The string Go ahead…> is printed and the program waits for input (see read on the next line).

  7. The read command assigns user input to the built-in REPLY variable.

  8. If the value of REPLY matches Stop or stop, the break command causes the loop to exit and the program will terminate. Entering Stop or stop is the only way we will get out of this program unless it is killed with the kill command.

  9. The break command causes the body of the loop to be exited.

  10. The done keyword marks the end of the loop.

Resetting Signals

To reset a signal to its default behavior, the trap command is followed by the signal name or number.

Example 9.66.
						trap 2
					

Explanation

Resets the default action for signal 2, SIGINT, which is used to kill a process, i.e., Control-C.

Example 9.67.
						trap trap 2' 2
					

Explanation

Sets the default action for signal 2 (SIGINT) to execute the command string within quotes when the signal arrives. The user must press Control-C twice to terminate the program. The first trap catches the signal, the second trap resets the trap back to its default action, which is to kill the process.

Traps in Functions

If you use a trap to handle a signal in a function, it will affect the entire script, once the function is called. The trap is global to the script. In the following example, the trap is set to ignore the interrupt key, ^C. This script had to be killed with the kill command to stop the looping. It demonstrates potential undesirable side effects when using traps in functions.

Example 9.68.
(The Script)
   #!/bin/bash
1  function trapper () {
         echo "In trapper"
2        trap 'echo "Caught in a trap!" 'INT
         # Once set, this trap affects the entire script. Anytime
         # ^C is entered, the script will ignore it.
   }
3  while:
   do
         echo "In the main script"
4        trapper
5        echo "Still in main"
         sleep 5
   done
(The Output)
$ trapper
						In the main script
						In trapper
						Still in main
						^CCaught in a trap!
						In the main script
						In trapper
						Still in main
						^CCaught in a trap!
						In the main script
					

Explanation

  1. The trapper function is defined. All variables and traps set in the function are global to the script.

  2. The trap command will ignore INT, signal 2, the interrupt key (^C). If ^C is pressed, the message Caught in a trap is printed, and the script continues forever. The script can be killed with the kill command or Ctrl-.

  3. The main script starts a forever loop.

  4. The function trapper is called.

  5. When the function returns, execution starts here.

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

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