Saturday, February 20, 2016

Linux Signal as normal code execution with Handler


Ctrl-C would send SIGINT and can be capture by a handler on a fork. some other signal kill -TERM 123, kill -HUP 123, pgrep sleep, kill -INT 123

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void handler(int sigtype)
{
 printf("type: %d\n",sigtype);
}

struct sigaction make_sigaction()
{
 struct sigaction a;
 a.sa_handler=handler;
 a.sa_flags=SA_RESTART;
 a.sa_flags=0;
 sigemptyset(&a.sa_mask);

return a;
}

int main()
{
 struct sigaction a=make_sigaction();
 sigaction(SIGINT,&a,NULL);
// signal(SIGINT,SIG_IGN);  // will ignore handler ctrl+c
// signal(SIGQUIT,SIG_IGN); // ignore ctrl+backslash
 int c;
 while(1)
 {
   printf("%d\n",c++);
   sleep(1);
 }
}

Note: (1)can create a blocking call instead of a busy while above
           int p[2]; 
           pipe(p); 
           while (1) {
              read(p[0],buf,1000);  .....
           } 
      (2) sigaction with alarm and read blocking call can have a read with timeout

          SIGALRM will cause system call to return after timeout

          sigaction(SIGALRM, &action, NULL);
          alarm(3);
          int n = read(0,line,100);  // after 3 sec, no longer blocking
          alarm(0); //cxl alarm
          if(n==-1 && errno==EINTR) return -1;

No comments:

Post a Comment