The Linux Programming Interface

(nextflipdebug5) #1
Signals: Fundamental Concepts 401

various example programs, we’ll nevertheless call printf() from a signal handler as a
simple means of seeing when the handler is called.

Listing 20-2: Establishing the same handler for two different signals
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––signals/intquit.c
#include <signal.h>
#include "tlpi_hdr.h"

static void
sigHandler(int sig)
{
static int count = 0;

/* UNSAFE: This handler uses non-async-signal-safe functions
(printf(), exit(); see Section 21.1.2) */

if (sig == SIGINT) {
count++;
printf("Caught SIGINT (%d)\n", count);
return; /* Resume execution at point of interruption */
}

/* Must be SIGQUIT - print a message and terminate the process */

printf("Caught SIGQUIT - that's all folks!\n");
exit(EXIT_SUCCESS);
}

int
main(int argc, char *argv[])
{
/* Establish same handler for SIGINT and SIGQUIT */

if (signal(SIGINT, sigHandler) == SIG_ERR)
errExit("signal");
if (signal(SIGQUIT, sigHandler) == SIG_ERR)
errExit("signal");

for (;;) /* Loop forever, waiting for signals */
pause(); /* Block until a signal is caught */
}
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––signals/intquit.c

20.5 Sending Signals: kill()...............................................................................................


One process can send a signal to another process using the kill() system call, which
is the analog of the kill shell command. (The term kill was chosen because the
default action of most of the signals that were available on early UNIX implementa-
tions was to terminate the process.)
Free download pdf