The Linux Programming Interface

(nextflipdebug5) #1
Signals: Fundamental Concepts 413

pid = getLong(argv[1], 0, "PID");
numSigs = getInt(argv[2], GN_GT_0, "num-sigs");
sig = getInt(argv[3], 0, "sig-num");


/ Send signals to receiver /


printf("%s: sending signal %d to process %ld %d times\n",
argv[0], sig, (long) pid, numSigs);


for (j = 0; j < numSigs; j++)
if (kill(pid, sig) == -1)
errExit("kill");


/ If a fourth command-line argument was specified, send that signal /


if (argc > 4)
if (kill(pid, getInt(argv[4], 0, "sig-num-2")) == -1)
errExit("kill");


printf("%s: exiting\n", argv[0]);
exit(EXIT_SUCCESS);
}
–––––––––––––––––––––––––––––––––––––––––––––––––––––– signals/sig_sender.c


The program shown in Listing 20-7 is designed to catch and report statistics on sig-
nals sent by the program in Listing 20-6. This program performs the following steps:


z The program sets up a single handler to catch all signals w. (It isn’t possible to
catch SIGKILL and SIGSTOP, but we ignore the error that occurs when trying to
establish a handler for these signals.) For most types of signals, the handler q
simply counts the signal using an array. If SIGINT is received, the handler sets a
flag (gotSigint) that causes the program to exit its main loop (the while loop
described below). (We explain the use of the volatile qualifier and the
sig_atomic_t data type used to declare the gotSigint variable in Section 21.1.3.)


z If a command-line argument was supplied to the program, then the program
blocks all signals for the number of seconds specified by that argument, and
then, prior to unblocking the signals, displays the set of pending signals e. This
allows us to send signals to the process before it commences the following step.


z The program executes a while loop that consumes CPU time until gotSigint is
set r. (Sections 20.14 and 22.9 describe the use of pause() and sigsuspend(),
which are more CPU-efficient ways of waiting for the arrival of a signal.)


z After exiting the while loop, the program displays counts of all signals received t.


We first use these two programs to illustrate that a blocked signal is delivered only
once, no matter how many times it is generated. We do this by specifying a sleep
interval for the receiver and sending all signals before the sleep interval completes.


$ ./sig_receiver 15 & Receiver blocks signals for 15 secs
[1] 5368
./sig_receiver: PID is 5368
./sig_receiver: sleeping for 15 seconds
Free download pdf