[ACCEPTED]-call a function when the program is finished with ctrl c-function

Accepted answer
Score: 10

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

Here's an example 2 that I ran across recently ("Tap the interrupt signal") and modified 1 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;
}
Score: 8

For a full working example you can try the 1 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
Score: 4

You have to catch the SIGINT. Something 1 like this:

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

loads more detail here

Score: 0

Short answer: look into the signal function, specifically 6 catching SIGINT. You write a callback function 5 and pass it to the system via the signal 4 function, then when that particular signal 3 happens, the system calls your callback 2 function. You can close files and do whatever 1 other cleanup stuff you want in there.

Score: 0

Note to people who might stumble upon this 3 question, looking for the answer in Windows instead:

Use 2 the SetConsoleCtrlHandler API call to set a custom handler and 1 watch for CTRL_C_EVENT, CTRL_BREAK_EVENT or CTRL_CLOSE_EVENT.

More Related questions