Link to home
Start Free TrialLog in
Avatar of dmorgor
dmorgor

asked on

setjmp() and signal handling

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;
}
ASKER CERTIFIED SOLUTION
Avatar of zebada
zebada

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dmorgor
dmorgor

ASKER

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

dave