Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    How to intercept console aplication exit ?

    General and Desktop
    1
    2
    3481
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • A
      Anticross last edited by

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

      MyClass manager(NULL);
      
      manager.start();
      
      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 ?

      1 Reply Last reply Reply Quote 0
      • ?
        Guest last edited by

        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
        switch(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]);
        }
        free(strs);*/
        
        //...   (do something else)
        
        //app ends as expected
        fprintf(stderr, "Thus ends!!");
        QApplication::quit();
        

        }@

        1 Reply Last reply Reply Quote 0
        • First post
          Last post