Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a function when the program is finished with ctrl c

Tags:

function

linux

I am working in the Linux environment, and I have a C++ program, what I want is when I cancel the program with ctrl+c I would like that the program executes a function, to close some files and print some sutff, is there any way to do this?. Thank you.

like image 987
Eduardo Avatar asked Dec 15 '08 16:12

Eduardo


3 Answers

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;
}
like image 80
d_schnell Avatar answered Sep 30 '22 03:09

d_schnell


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
like image 37
Jay Avatar answered Sep 30 '22 03:09

Jay


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

like image 37
Colin Pickard Avatar answered Sep 30 '22 02:09

Colin Pickard