1

I am developing a multithread application running on linux pc kernel version 4.4.14. I want to track some catastrophic errors causing segmentation fault. I set up a signal handler linked to SIGSEGV to try to get the pid number of the thread causing the crash. The handler function code is the following:

void sighandler(int signum, siginfo_t *siginfo, void *context)  
{
    // get pid of sender,
  pid_t sender_pid = siginfo->si_pid;
  printf("Process %d got signal %d SEG FAULT !!!\n", (int)sender_pid, signum);
  fflush(stdout);
  sleep(1);
  printf("Stdout Flushed %d got signal %d SEG FAULT !!!\n", sender_pid, signum);
  trappola.sa_flags = 0;
    trappola.sa_handler = SIG_DFL;
    sigaction(signum, &trappola, NULL);
  kill(getpid(), signum);
  exit(-1);
}

and in the main() I link the sighandler function using:

struct sigaction trappola;  
memset(&trappola, 0x00, sizeof(trappola));

trappola.sa_flags = SA_SIGINFO;
trappola.sa_sigaction = sighandler;
sigaction(SIGSEGV, &trappola, NULL);

the handler is working but I am not able to get the pid of the thread causing the fault. The printf:

printf("Process %d got signal %d SEG FAULT !!!\n", (int)sender_pid, signum);

always print different numbers as sender_pid none of which are meaningful. Why I cannot get the pid of the offending thread ?

Where I am wrong ? How can I get the pid of the offending thread in the handler function ?

Thank you very much for any help.

Regards.

Marco Bisio

mrcbis
  • 91
  • 1
  • 7

1 Answers1

0

siginfo->si_pid is not meaningful because the thread causing the SIGSEGV (at address siginfo->si_addr) is the same thread that receives the signal.

See the signal(7) manpage:

A signal may be generated (and thus pending) for a process as a whole (e.g., when sent using kill(2)) or for a specific thread (e.g., certain signals, such as SIGSEGV and SIGFPE, generated as a consequence of executing a specific machine-language instruction are thread directed (...)

xhienne
  • 5,738
  • 1
  • 15
  • 34
  • Thank you very much for your answer. Be patient but the thread trowing sigsegv seems to me to be no the same receiving the signal within the handler. I mean: the main() install the handler and run the thread using pthread_create....; after that the thread has an own pid number. I expected to be able to read that pid number from the handler using siginfo->si_pid; Thank you again Marco Bisio – mrcbis Sep 29 '17 at 09:07
  • @mrcbis You don't tell us what makes you thing this is not the same thread. Use a debugger (`gdb`) and you will know what causes the segfault. – xhienne Sep 29 '17 at 09:15