lecardo
lecardo

Reputation: 1212

How to catch a signal properly in C

I been focusing on many ways on catching signals. The latest one being is using a global variable. My aim is to catch control C, when its pressed, it sets a flag to "1" that then triggers some code to run.

my problem is, I can get the signal to be caught. However finding it impossible to run the code that should run in the if statement.

void handleSignal (int signal);

int signalAction = 0;

int main ()
{
    //catch signal control C
    if (signal(SIGINT, handleSignal) == SIG_ERR)
    {
        write (2, "Error catching signal C \n", 26);
    }

    if (signalAction == 1)
    {
        write(1, "WOOO CONTROL C \n", 16);
        signalAction = 0;
    }

    printf("%d \n", signalAction);

    while(1)
        sleep(1);   
}

void handleSignal (int signal)
{
    if (signal == SIGINT)
    {
        write(1, "ContrlC \n", 11);
        signalAction = 1;
    }
}

When control c is pressed I get "contrlC" printed out from the signal handler. However the if statement in the main function if(signalAction ==1).... doesn't run.

The variable must be set to 1. Is their a issue in main picking it up for some reason?

Upvotes: 2

Views: 2991

Answers (1)

helloV
helloV

Reputation: 52393

Move your if(signalAction ==1) inside while loop

Upvotes: 5

Related Questions