Wednesday, August 24, 2011

Registering a Signal Handler

A signal handler can be registered using

  • sighandler_t signal(int signum, sighandler_t handler);
     The handler has the following prototype : 
     void handler(int signum)
  • int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); 
    -> The sigaction structure contains the reference to the handler.
    -> The handler can have two different prototypes.
       void handler(int signum)
       void handler(int signum, siginfo_t *info, void *data)

Inside the handler code, only some functions can be used : only
the asyncsignalsafe functions, as documented by signal(7).

See an example below how to use the above api's.

#include <signal.h>
#include <assert.h>
#include <unistd.h>
#include <stdio.h>

void myhandler(int signum) {
   printf("Signal catched!\n");
}
int main(void{
   int ret;
   struct sigaction action = {
      .sa_handler = myhandler,
   };
   ret = sigaction(SIGUSR1, & action, NULL);
   assert(ret == 0);
   while(1);
   return 0;
}

No comments:

Post a Comment