A signal is a notification to a process that an event has occurred. Signals are sometimes described as softwareinterrupts.
The usual source of many signals sent to a process is the kernel.
Below the types of events that cause the kernel to generate a signal:
A hardware exeption occured Examples: marformed machine-language instruction, dividing by 0, inaccessible memory referencing.
The user typed one of the terminal special character Examples:Control-C, Control-Z
A software event ocurred Examples: terminal windows was resized, timer went off, CPU limits or child process is terminated.
Process' actions on signal
Depending on the signal, a process may act different:
The signal is ignored.
The process is terminated (killed).
A coredump file is generated.
The process is stopped.
Execution of the process is resumed after previously being stopped.
Alternatively, a program may change the default behavior (also known as disposition) by:
Allowing defaultaction occur.
The signal is ignored.
A signalhandler is executed.
Signal types and default actions
Signal Handlers
(Signal dispositions)
A signal handler (also known as signalcatcher) is a function, written by the programmer, that performs appropriate tasks in response to the delivery of a signal.
#include <signal.h>
static void sigHandler(int sig) {
printf("Ouch!\n"); /* UNSAFE (see Section 21.1.2) */
}
int main(int argc, char *argv[]) {
int j;
if (signal(SIGINT, sigHandler) == SIG_ERR) errExit("signal");
for (j = 0; ; j++) {
printf("%d\n", j);
sleep(3);
}
}
Source Code: signals/ouch.c and signals/intquit.c from TLPI.
Sending Signals
int kill(pid_t pid, int sig)
One process can send a signal to another process using the kill() system call, which is the analog of the kill shell command.
int raise(int sig)
Sometimes, it is useful for a process to send a signal to itself.
In a single-threaded program, a call to raise() is equivalent to the following call to kill()
kill(getpid(), sig)
int killpg(pid_t pgrp, int sig);
The killpg() function sends a signal to all of the members of a process group.