Example of a C Signal Handler

The following code gives a simple example of a signal handler function for a single-thread program. It shows how your program can recover from a signal and continue to run successfully.

In the example, the function chkptr checks a given number of bytes in an area of storage and returns the number of bytes that you can access. Key lines in the program are linked to explanations below the sample.

#include <signal.h>
#include <setjmp.h>
#include <string.h>
#include <io.h>

static void mysig(int sig);        /* signal handler prototype */
static jmp_buf jbuf;               /* buffer for machine state */

int chkptr(void * ptr, int size)
{
   void (* oldsig)(int);           /* where to save the old signal handler */
   volatile char c;                /* volatile to ensure access occurs */
   int valid = 0;                  /* count of valid bytes */
   char * p = ptr;
   oldsig = signal(SIGSEGV,mysig); /* set the signal handler */
   if (!setjmp(jbuf))              /* provide a point for the */ 
   {                               /* signal handler to return to */
      while (size--)
      { 
         c = *p++;                 /* check the storage and */ 
         valid++;                  /* increase the counter */ |
      }
   }
   signal(SIGSEGV,oldsig);         /* reset the signal handler */ 
   return valid;                   /* return number of valid bytes */ 
}

static void mysig(int sig)
{                                  /* write to file handle 2(stderr) */
   char FileData[20];
   strcpy(FileData, "Signal Occurred.\n\r");
   write(2, FileData, 18)
                           /* return to the point of the setjmp call */ 
   longjmp(jbuf,1);
}

Signal handling is controlled by the statments in the code as follows:



Signals and Exceptions
Signal and Exception Handling