|
|
|||
![]() |
Department of Engineering |
| University of Cambridge > Engineering Department > computing help |
Various signals (interrupts) can be received by your program. See the signal.h include file for a list. You can trap them if you wish, or simply ignore them. E.g.
#include <signal.h> ... /* this will ignore control-C */ signal(SIGINT, SIG_IGN);
The following code sets a `timebomb'. After Timer is called, the program will continue execution until `n' milliseconds have passed, then normal execution will be interrupted and `onalarm()' will be called before normal execution is resumed.
#include <signal.h>
static void onalarm(void)
{
something();
signal(SIGALRM,SIG_DFL);
}
...
void Timer(int n) /* waits for 'n' milliseconds */
{
long usec;
struct itimerval it;
if (!n) return;
usec = (long) n * 1000;
memset(&it, 0, sizeof(it));
if (usec>=1000000L) { /* more than 1 second */
it.it_value.tv_sec = usec / 1000000L;
usec %= 1000000L;
}
it.it_value.tv_usec = usec;
signal(SIGALRM,onalarm);
setitimer(ITIMER_REAL, &it, (struct itimerval *)0);
}
This same method can be used to catch emergency signals like SIGBUS (bus error) too.