Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Installing signal handler in C

I am trying to catch a SIGSEGV from my program. I got a problem that my signal_handler doesn't catch the signal.

void handler(int sig){
  printf("catch SIGSEGV");
  exit(EXIT_FAILURE);
}


void foo(){
   struct sigaction sa;
   sa.sa_flags = SA_SIGINFO;
   sigemptyset(&sa.sa_mask);
   sa.sa_handler = handler;
   if(sigaction(SIGSEGV, &sa, NULL) == -1){
       handle_error("sigaction");
   }
   /* if SIGSEGV happen here, I can catch it */
   bar();
}

void bar() {
     /* if SIGSEGV happen here, I cannot catch it */
}

Is that means I have to install another signal handler inside bar?

But what if I have a bunch of function that want to catch the same signal. I have to install the signal handler for multiple times?

Update :

I tried to install the handler directly in the function but still cannot catch it. So I think it might be other problem. But that pretty weird. I use gdb to run and get

Program received signal SIGSEGV, Segmentation fault.
0x080499b1 in is_printable_string (
    str=0xb80fe768 <Address 0xb80fe768 out of bounds>)
    at trace/trace.c:259
259   while(str[index]!='\0'){

and this is my is_printable_String

int is_printable_string(char *str){
 struct sigaction sa;
  sa.sa_flags = SA_SIGINFO;
  sigemptyset(&sa.sa_mask);
  sa.sa_sigaction = handler;
  if(sigaction(SIGSEGV, &sa, NULL) == -1){
    handle_error("sigaction");
  }
  int index;
  index=0;
  while(str[index]!='\0'){
     if(!isprint(str[index])){
          return -1;
      }
  index++;
  }
  /* continue... */

This seems like I got a SEG fault, but I can't catch it

I intentionally passed that pointer, so nothing wrong with str parameter.

like image 790
Timothy Leung Avatar asked Jul 18 '26 13:07

Timothy Leung


1 Answers

from the man page of sigaction ...

SA_SIGINFO (since Linux 2.2) The signal handler takes three arguments, not one. In this case, sa_sigaction should be set instead of sa_handler. This flag is only meaningful when establishing a signal handler.

Therefore, your issue should be the line

sa.sa_flags = SA_SIGINFO;

Change it to

sa.sa_flags = 0;

and see how it goes.

like image 91
ajcaruana Avatar answered Jul 20 '26 09:07

ajcaruana