Run something once the program has been terminated using CTRL+C

228 views Asked by At

Is there any way to run a function before a program terminates? eg. the user presses ctrl+c and you want to print something to them. Thanks!

1

There are 1 answers

7
Levi On

For *nix systems, you can use the signal() function.

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

volatile sig_atomic_t sig_flag = 0;

void sig_handler(int sig)
{
    // A signal has been received. Set `sig_flag` to the value of the signal
    sig_flag = sig;
}

int main()
{
    // Call sig_handler on SIGINT (Ctrl-C)
    signal(SIGINT, sig_handler);

    while (sig_flag != SIGINT);
    printf("Bye\n");

    return 0;
}

EDIT: As per Basile's comment, I should mention that only a select few functions are safe to use under a signal handler, as the handler is called asynchronously. The list of safe functions are available under signal(7)