Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

372 Signals Chapter 10


When we terminate thesleepcall with the interrupt signal, thepr_exitfunction
(Figure8.5) thinks that it terminated normally.The same thing happens when we kill
thesleepcall with the quit key.Asthis example demonstrates, the Bourne shell has a
poorly documented feature in which its termination status is 128 plus the signal
number,when the command it was executing is terminated by a signal.We can see this
with the shell interactively.

$sh make surewe’rerunning the Bourne shell
$sh -c "sleep 30"
ˆC press the interrupt key
$echo $? print termination status of last command
130
$sh -c "sleep 30"
ˆ\sh: 962 Quit - core dumped press the quit key
$echo $? print termination status of last command
131
$exit leave Bourne shell

On the system being used,SIGINThas a value of 2 andSIGQUIThas a value of 3,
giving us the shell’s termination statuses of 130 and 131.
Let’s try a similar example, but this time we’ll send a signal directly to the shell and
see what is returned bysystem:

$tsys "sleep 30" & start it in background this time
9257
$ps -f look at the process IDs
UID PID PPID TTY TIME CMD
sar 9260 949 pts/5 0:00 ps -f
sar 9258 9257 pts/5 0:00 sh -c sleep 30
sar 949 947 pts/5 0:01 /bin/sh
sar 9257 949 pts/5 0:00 tsys sleep 30
sar 9259 9258 pts/5 0:00 sleep 30
$kill -KILL 9258 kill the shell itself
abnormal termination, signal number = 9

Here, we can see that the return value fromsystemreports an abnormal termination
only when the shell itself terminates abnormally.

Other shells behave differently when handling terminal-generated signals, such asSIGINT
andSIGQUIT.Withbashanddash,for example, pressing the interrupt or quit key will result
in an exit status indicating abnormal termination with the corresponding signal number.
However, if we find our process executingsleepand send it a signal directly, so that the
signal goes only to the individual process instead of the entireforeground process group, we
will find that these shells behave like the Bourne shell and exit with a normal termination
status of 128 plus the signal number.

When writing programs that use thesystemfunction, be sure to interpret the
return value correctly.Ifyou callfork,exec,andwaityourself, the termination
status is not the same as if you callsystem.
Free download pdf