9.8. Signal handlingTwo functions allow for asynchronous event handling to be provided.
A signal is a condition that may be reported during program
execution, and can be ignored, handled specially, or, as is the default,
used to terminate the program. One function sends signals, another is used
to determine how a signal will be processed. Many of the signals may be
generated by the underlying hardware or operating system as well as by means
of the signal-sending function The signals are defined in the include file
Some implementations may have additional signals available, over and above
this standard set. They will be given names that start The function #include <signal.h> void (*signal (int sig, void (*func)(int)))(int); That is to say, Two special values may be used as the If the call to When a signal event happens which is not being ignored, if the
associated func is a pointer to a function, first the equivalent of
Next, a call is made to the signal-handling function. If that
function returns normally, then under most circumstances the
program will resume at the point where the event occurred. However, if the
value of The following program fragment shows the use of signal to perform a tidy exit to a program on receipt of the interrupt or ‘interactive attention’ signal.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
FILE *temp_file;
void leave(int sig);
main() {
(void) signal(SIGINT,leave);
temp_file = fopen("tmp","w");
for(;;) {
/*
* Do things....
*/
printf("Ready...\n");
(void)getchar();
}
/* can't get here ... */
exit(EXIT_SUCCESS);
}
/*
* on receipt of SIGINT, close tmp file
* but beware - calling library functions from a
* signal handler is not guaranteed to work in all
* implementations.....
* this is not a strictly conforming program
*/
void
leave(int sig) {
fprintf(temp_file,"\nInterrupted..\n");
fclose(temp_file);
exit(sig);
}Example 9.4It is possible for a program to send signals to itself by means of the
include <signal.h> int raise (int sig); The signal sig is sent to the program.
#include <signal.h>
void
abort(void) {
raise(SIGABRT);
}
If a signal occurs for any reason other than calling abort or raise,
the signal-handling function may only call signal or assign a value to
a volatile static object of type |
The C BookThis book is published as a matter of historical interest. Please read the copyright and disclaimer information. GBdirect Ltd provides up-to-date training and consultancy in C, Embedded C, C++ and a wide range of other subjects based on open standards if you happen to be interested. |
|
West Yorkshire Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday South East Regional Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday Please note: |