How to intercept console aplication exit ?

  • I've got console application. The main.cpp
    @QCoreApplication a(argc, argv);

    MyClass manager(NULL);
    return a.exec();@

    I do some manipulations with files inside MyClass class and if I close command line console and interrupt executing of my program it lost all data from unclosed file. Is there some way to intercept exit of my app. and save file before close ?

  • You may try to register a custom function to a signal (i.e.: SIGTERM) so, when the signal is sent to your app, your function does its job, then the app closes as it does now.

    Code is as follows:

    @#include <signal.h>
    void signalHandler(int signal);

    int main(...){
    //configure app's reaction to OS signals
    struct sigaction act, oact;
    memset((void*)&act, 0, sizeof(struct sigaction));
    memset((void*)&oact, 0, sizeof(struct sigaction));
    act.sa_flags = 0;
    act.sa_handler = &signalHandler;
    sigaction(SIGINT, &act, &oact);
    sigaction(SIGKILL, &act, &oact);
    sigaction(SIGQUIT, &act, &oact);
    sigaction(SIGSTOP, &act, &oact);
    sigaction(SIGTERM, &act, &oact);
    sigaction(SIGSEGV, &act, &oact);

    void signalHandler(int signal)
    //print received signal
    case SIGINT: printf("SIGINT => "); break;
    case SIGKILL: printf("SIGKILL => "); break;
    case SIGQUIT: printf("SIGQUIT => "); break;
    case SIGSTOP: printf("SIGSTOP => "); break;
    case SIGTERM: printf("SIGTERM => "); break;
    case SIGSEGV: printf("SIGSEGV => "); break;
    default: printf("APPLICATION EXITING => "); break;

    //print call stack (needs #include <execinfo.h>)
    /*int callstack_size = 2048;
    void* callstack[callstack_size];
    int i, frames = backtrace(callstack, callstack_size);
    char** strs = backtrace_symbols(callstack, frames);
    for(i = 0; i &lt; frames; i++){
        printf("%s\n", strs[i]);
    //...   (do something else)
    //app ends as expected
    fprintf(stderr, "Thus ends!!");


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.