Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 10.3 signalFunction 325


We invoke the program in the background and use thekill( 1 )command to send it
signals. Note that the termkillin the UNIX System is a misnomer.Thekill( 1 )
command and thekill( 2 )function just send a signal to a process or process group.
Whether that signal terminates the process depends on which signal is sent and
whether the process has arranged to catch the signal.
$./a.out & start process in background
[1] 7216 job-control shell prints job number and process ID
$kill -USR1 7216 send itSIGUSR1
received SIGUSR1
$kill -USR2 7216 send itSIGUSR2
received SIGUSR2
$kill 7216 now send itSIGTERM
[1]+ Terminated ./a.out
When we send theSIGTERMsignal, the process is terminated, since it doesn’t catch the
signal, and the default action for the signal is termination.

Program Start-Up


When a program is executed, the status of all signals is either default or ignore.
Normally,all signals areset to their default action, unless the process that callsexecis
ignoring the signal. Specifically,theexecfunctions change the disposition of any
signals being caught to their default action and leave the status of all other signals
alone. (Naturally,asignal that is being caught by a process that callsexeccannot be
caught by the same function in the new program, since the address of the signal-
catching function in the caller probably has no meaning in the new program file that is
executed.)
One specific example of this signal status behavior is how an interactive shell treats
the interrupt and quit signals for a background process. With a shell that doesn’t
support job control, when we execute a process in the background, as in
cc main.c &
the shell automatically sets the disposition of the interrupt and quit signals in the
background process to be ignored. This is done so that if we type the interrupt
character, it doesn’t affect the background process. If this weren’t done and we typed
the interrupt character, it would terminate not only the foreground process, but also all
the background processes.
Many interactive programs that catch these two signals have code that looks like
void sig_int(int), sig_quit(int);
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, sig_int);
if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
signal(SIGQUIT, sig_quit);
Following this approach, the process catches the signal only if the signal is not currently
being ignored.
Free download pdf