Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on_exit and CTRL+C

Tags:

c

posix

I've got a small program that opens a file and does some operation on it. I subscribed the file closure to the program termination as follows:

static
void exit_handler (int ev, void *arg)
{
    fprintf(stderr, "bye %d\n", WEXITSTATUS(ev));
    fclose((FILE *)arg);
}

int main (int argc, char *argv[])
{
    FILE *out;

    ...

    out = fopen(argv[1], "wt");
    if (out == NULL) {
        perror("Opening output file");
        exit(EXIT_FAILURE);
    }
    on_exit(exit_handler, out);

    ...
}

Trying to execute this I notice that it works properly only if the program terminates normally. In case of CTRL+C (SIGINT) the exit_handler callback is not executed.

Isn't that weird? Should I associate a exit(EXIT_FAILURE) call to the signal handler for SIGTERM? What is the best practice in this case?

like image 533
Dacav Avatar asked Oct 27 '25 04:10

Dacav


1 Answers

on_exit will not be invoked for SIGTERM signals. You need to add a handler for it with signal. For example:

void signalHandler(void)
{
  ...
}

int main(void)
{
  signal(SIGTERM, signalHandler);
}

Also note that SIGKILL can not be caught by design.

like image 186
Mike Kwan Avatar answered Oct 29 '25 17:10

Mike Kwan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!