Mari
Mari

Reputation: 35

Signal handling in C: program continues executing even after interruption

I do not understand why when I run this code and then use a control+C interrupt the program closes immediately but the log file shows "program ran successfully". How can I make it print the correct message?

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

static volatile int globalFlag = 0;

void handler();

int main()
{
    FILE* log;
    log = fopen("log.txt", "a");
    signal(SIGINT, handler);
    while(globalFlag == 0){

        sleep(20);
        fprintf(log, "program ran successfully\n");
        fclose(log);

        return 0;
    }
    fprintf(log, "program shut by signal\n");
    fclose(log);
    return -1;

}

void handler()
{

    globalFlag = 1;

}

Upvotes: 0

Views: 125

Answers (2)

user4822941
user4822941

Reputation:

I'm quite confused by 'It seems I had misunderstood what control+C does.' so let me have a longer take here.

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

static volatile int globalFlag = 0;

The type should be sig_atomic_t. The variable is already 0. Bad name.

void handler();

Handlers are supposed to accept an int. Bad name. Can be made static.

int main()

Should be 'void'.

{
    FILE* log;
    log = fopen("log.txt", "a");

Missing error checking.

signal(SIGINT, handler);

So here the handler is installed...

while(globalFlag == 0){

... the flag is immediately checked ...

    sleep(20);
    fprintf(log, "program ran successfully\n");
    fclose(log);

... and the program exits because you have not managed to send the signal fast enough.

        return 0;
    }
    fprintf(log, "program shut by signal\n");
    fclose(log);
    return -1;

}

The issue would have been trivially debugged by running a simple thought experiment.

Upvotes: 1

Bill Lynch
Bill Lynch

Reputation: 81916

You likely wanted the sleep statement to be outside of the while loop.

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

static volatile int globalFlag = 0; 

void handler() { 
    globalFlag = 1; 
} 

int main() { 
    FILE* log; 
    log = fopen("log.txt", "a"); 
    signal(SIGINT, handler); 
    sleep(20); 

    if (globalFlag == 0){ 
        fprintf(log, "program ran successfully\n"); 
        fclose(log); 
        return 0; 
    } else { 
        fprintf(log, "program shut by signal\n"); 
        fclose(log); 
        return -1; 
    } 
} 

Upvotes: 1

Related Questions