This program is a simple demonstration of signals. Signals are like sofware interrupts, that are used to inform a process of the occurence of an event. Programs can be designed to catch a a signal, by providing a function to handle it.
For example, when shutting down a Linux box, the SIGTERM signal is sent to all processes. Processes that catch this signal, can properly terminate (e.g. de-allocate resources, close all open files).
sighandler_t signal(int signum, sighandler_t handler);
The signal() function associates a specific signal identified by signum with the new function specified by handler.
The signal() function can be used to install a handler for specific signals like SIGINT. SIGINT is the signal sent to the program when the user presses Ctrl-C. If the program should not exit when this happens, and should instead do something else, a new handler function must be associated with the SIGINT signal.
There are a number of signals available. In the program below, three signals are caught by the provided signal handler functions.
Try sending signals to this program through the command-line using the kill utility. First run the program in the background:
./signals-ex &
Then try sending a signal, for example:
kill -SIGHUP pid
Try killing the process:
kill pid
What signal does kill send a process by default?
Replace pid with the one the program displays upon startup.
Associating a signal with SIG_IGN will cause the program to ignore the signal. To reset the default signal handler, use SIG_DFL, as the second parameter of signal().
signals-ex.c (download)
/* Includes */
#include
#include
#include
/* This will be our new SIGINT handler.
SIGINT is generated when user presses Ctrl-C.
Normally, program will exit with Ctrl-C.
With our new handler, it won't exit. */
void mysigint()
{
printf("I caught the SIGINT signal!\n");
return;
}
/* Our own SIGKILL handler */
void mysigkill()
{
printf("I caught the SIGKILL signal!\n");
return;
}
/* Our own SIGHUP handler */
void mysighup()
{
printf("I caught the SIGHUP signal!\n");
return;
}
/* Our own SIGTERM handler */
void mysigterm()
{
printf("I caught the SIGTERM signal!\n");
return;
}
int main()
{
/* Use the signal() call to associate our own functions with
the SIGINT, SIGHUP, and SIGTERM signals */
if (signal(SIGINT, mysigint) == SIG_ERR)
printf("Cannot handle SIGINT!\n");
if (signal(SIGHUP, mysighup) == SIG_ERR)
printf("Cannot handle SIGHUP!\n");
if (signal(SIGTERM, mysigterm) == SIG_ERR)
printf("Cannot handle SIGTERM!\n");
/* can SIGKILL be handled by our own function? */
if (signal(SIGKILL, mysigkill) == SIG_ERR)
printf("Cannot handle SIGKILL!\n");
while(1); /* infinite loop */
/* exit */
exit(0);
} /* main() */
No comments:
Post a Comment