VMS-to-Unix Phrase Book
<=  Return           

3.6  Trapping Signals

Problem

You want to catch all possible ways a program can exit or die.

Solution

Good luck.

Discussion

Consider the following script:

#!/bin/sh
#
#    Demo a process dying because of an interrupt signal and how
#    there is no chance to even test for an exit status.

     ./bail-out.pl i 8
     echo "exit status is: $?"

#==[ EOF: bail-out-shell-test.sh ]==

When we execute this script, we get:
unix> ./bail-out-shell-test.sh
bail-out.pl: killing myself with '8' signal
unix>
Notice that the echo was never executed. This means the program not only didn't exit with an error status, in the process of dying, it took the script with it. This is because the script was not prepared to trap this interrupt signal thrown by the sample program An example of an interrupt that can kill a program dead would be a division by zero error. This particular sample program was written for Linux, so some changes would be needed to make this program's output text correct for other Unix systems. This is because such signals and their definitions vary from Unix to Unix. This sample script was designed to illustrate how a script can attempt to catch anticipated errors. Again the instructions displayed would need to be changed for systems other than Linux. For example, under Tru-64, the statement
trap 'echo "$0: expected signal";
      final=2;                                  # Our exit code for signals
      exit;                                     # we are expecting.
     ' 3 6 8 11;
generates a scripting error. It turns out that signal 11 (which is the SEGV signal under Tru-64) isn't even trappable so the shell interpreter generates a scan-time error when it sees us trying to trap that particular signal. In other words, on some systems, you may not be able to trap for all signals even if you want to try to.

See Also

3.5 - Detecting Program Errors;
Chapter 10 of Unix for OpenVMS Users ;
Chapter 40 of Unix Power Tools .


<=  Return           

Colophon:
Best Viewed With Any Browser
This page maintained by:
    Bill.Costa@unh.edu
    of the Enterprise Computing Group
    in the dept of Computing & Information Sevices
    at the University of New Hampshire

Typographical
Conventions

Created:  31-Jan-2001 BC
Revised:  11-Apr-2001 BC