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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With