setjmp() and signal handling

dmorgor
dmorgor used Ask the Experts™
on
hi,

I have a program with a signal handler containing a call to longjmp(). It works the first time around, and after that the signal handler doesn't get called.

I have reproduced the problem with the following simple code:

#include <setjmp.h>
#include <stdio.h>
#include <time.h>
#include <signal.h>

jmp_buf saveState;

void myHandler(int sig);


int main(){

  int sand;
  struct sigaction handler;
 
  handler.sa_handler = myHandler;
 
  if(sigemptyset(&handler.sa_mask) < 0){
    perror("sigemptyset()");
    exit(1);
  }
  handler.sa_flags = 0;
 
  handler.sa_flags |= SA_RESTART;

  if(sigaction(SIGHUP, &handler, NULL) < 0){
    perror("HUP down");
    exit(1);
  }

  sand = setjmp(saveState);

  for(;;){
    fprintf(stderr, "Having a quick nap\n");
    sleep(5);
  }

  return 0;
}

void myHandler(int sig){
  fprintf(stderr, "  --> SIGHUP received!\n");
  longjmp(saveState, 42);
}


When the program is running and I send a SIGHUP from another terminal (kill -HUP pID), I get the SIGHUP received message. Future SIGHUPs do nothing.
But if I comment out the call to longjmp(), I can SIGHUP repeatedly.
I wrote another small program to test the setjmp() and longjmp() combination and that runs fine (see code below).
It seems that the jumps and the signal handler works fine in isolation but not together.
Does anyone know what I'm doing wrong?


Thanks,

Dave

/* simple jump test */
#include <setjmp.h>
#include <stdio.h>
#include <time.h>

int main(){
  jmp_buf env;
  int sand;

  sand = setjmp(env);

  for(;;){
    fprintf(stderr, "just a quick nap\n");
    sleep(1);
    longjmp(env, 42);
    fprintf(stderr, "should never get here\n");
  }
  return 1;
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
I'm not sure which platform you are on but on Linux:

NOTES
       POSIX  does  not  specify whether longjmp will restore the
       signal context.  If you want to save  and  restore  signal
       masks, use siglongjmp.

Author

Commented:
Thanks - that solved my problem. I should have RTFManPages!

dave

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial