[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: ANSI C Up: ANSI C for Programmers Previous: realloc

Signals and error handling

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.



Tim Love
1999-10-06