Graphics Programs Reference
In-Depth Information
printf("Caught signal %d\t", signal);
if (signal == SIGTSTP)
printf("SIGTSTP (Ctrl-Z)");
else if (signal == SIGQUIT)
printf("SIGQUIT (Ctrl-\\)");
else if (signal == SIGUSR1)
printf("SIGUSR1");
else if (signal == SIGUSR2)
printf("SIGUSR2");
printf("\n");
}
void sigint_handler(int x) {
printf("Caught a Ctrl-C (SIGINT) in a separate handler\nExiting.\n");
exit(0);
}
int main() {
/* Registering signal handlers */
signal(SIGQUIT, signal_handler); // Set signal_handler() as the
signal(SIGTSTP, signal_handler); // signal handler for these
signal(SIGUSR1, signal_handler); // signals.
signal(SIGUSR2, signal_handler);
signal(SIGINT, sigint_handler); // Set sigint_handler() for SIGINT.
while(1) {} // Loop forever.
}
is stuck looping, incoming signals will interrupt execution and call the
registered signal handlers. In the output below, signals that can be triggered
when finished, returns execution back into the interrupted loop, whereas
the
sigint_handler()
function exits the program.
reader@hacking:~/booksrc $ gcc -o signal_example signal_example.c
reader@hacking:~/booksrc $ ./signal_example
Caught signal 20 SIGTSTP (Ctrl-Z)
Caught signal 3 SIGQUIT (Ctrl-\)
Caught a Ctrl-C (SIGINT) in a separate handler
Exiting.
r
eader@hacking:~/booksrc $
Specific signals can be sent to a process using the
kill
command. By
default, the
kill
command sends the terminate signal (
SIGTERM
) to a process.
With the
-l
command-line switch,
kill
lists all the possible signals. In the
output below, the
SIGUSR1
and
SIGUSR2
signals are sent to the signal_example
program being executed in another terminal.