Kitcha
Kitcha

Reputation: 1731

Not going to sleep after SIGINT in C

I have the following code. How to bring the control back to cleanupCode() when I received SIGINT while sleeping? I don't want to use goto or jump. Calling cleanupCode inside handler is not an option.

sigHandler(int sig __atribute__((unused)) {

    loopFlag = 0; 
}

void cleanupCode() 
{  printf("Graceful exit \n");

} 
int main ()  {    
     while(loopFlag)
       sleep(600);
     cleanupCode(); 
}

Upvotes: 0

Views: 551

Answers (2)

Duck
Duck

Reputation: 27552

You have to set the signal handler somewhere.

#include <signal.h>
#include <unistd.h>

volatile int loopFlag = 1;

void sigHandler(int sig)
{
    loopFlag = 0;
}

void cleanupCode()
{
     printf("Graceful exit \n");
}

int main ()
{
    signal(SIGINT, sigHandler);

     while(loopFlag)
       sleep(600);

     cleanupCode();
}

Upvotes: 5

Jonathan Leffler
Jonathan Leffler

Reputation: 754280

This works for me:

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

typedef struct sigaction SigAction;
static volatile sig_atomic_t loopFlag = 1;

static void sigHandler(int signum __attribute__((unused)))
{
    loopFlag = 0; 
}

static void cleanupCode(void) 
{
    printf("Graceful exit\n");
} 

static void setSignals(void)
{
    SigAction action;
    sigfillset(&action.sa_mask);
    action.sa_handler = sigHandler;
    action.sa_flags = 0;
    sigaction(SIGINT, &action, 0);
}

int main(void)
{    
    setSignals();
    while (loopFlag)
        sleep(600);
    cleanupCode(); 
    return(0);
}

Upvotes: 4

Related Questions