call a function when the program is finished with ctrl c

signal() can be dangerous on some OSes and is deprecated on Linux in favor of sigaction(). "signal versus sigaction"

Here's an example that I ran across recently ("Tap the interrupt signal") and modified as I was playing around with it.

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

struct sigaction old_action;

void sigint_handler(int sig_no)
{
    printf("CTRL-C pressed\n");
    sigaction(SIGINT, &old_action, NULL);
    kill(0, SIGINT);
}

int main()
{

    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_handler = &sigint_handler;
    sigaction(SIGINT, &action, &old_action);

    pause();

    return 0;
}

For a full working example you can try the following code:

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

volatile bool STOP = false;
void sigint_handler(int sig);

int main() {
    signal(SIGINT, sigint_handler);
    while(true) {
        if (STOP) {
            break;
        }
    }
    return 0;
}

void sigint_handler(int sig) {
    printf("\nCTRL-C detected\n");
    STOP = true;
}

Example run:

[user@host]$ ./a.out 
^C
CTRL-C detected

You have to catch the SIGINT. Something like this:

void sigint_handler(int sig)
{
    [do some cleanup]
    signal(SIGINT, SIG_DFL);
    kill(getpid(), SIGINT);
}

loads more detail here

Tags:

Linux

Function