Windows Ctrl-C - Cleaning up local stack objects in command line app

前端 未结 2 1195
礼貌的吻别
礼貌的吻别 2021-01-26 11:05

I\'m writing a console application Windows that creates some objects in the main thread and kicks those off into a loop, only exiting when the user uses the Ctrl-C interrupt. <

相关标签:
2条回答
  • 2021-01-26 11:36

    You make your loop on a condition variable.

    When you receive ctrl-C (SIGINT) you set the condition variable to false and return. The loop will then exit normally.

    bool finished = false;
    
    int main()
    {
          DBClient db;
          DataPuller p;
    
          while (!finished)
          {
               // ... do stuff until Ctrl-C comes in
          }
    }
    
    // Signal handler or Control handler on windows
    // Set finished = true.
    
    0 讨论(0)
  • 2021-01-26 11:49

    I don't think this can be done without at least one global. However, I think you only need one:

    BOOL is_shutting_down = false;
    
    BOOL CtrlHandler ( DWORD fdwCtrlType ) {
        switch( fdwCtrlType ) 
        { 
            // Handle the CTRL-C signal. 
            case CTRL_C_EVENT: 
                is_shutting_down = true;
                return( TRUE );
        }
    }
    
    int main() {
          DBClient db;
          DataPuller p;
    
          while (is_shutting_down == false) {
               ... do stuff until Ctrl-C comes in
          }
    
          //objects clean themselves automatically.
    }
    

    A side affect of a global "is_shutting_down" is that if it is set to true, destructors do not need to deallocate memory, since the OS will automatically reclaim it all anyway, which allows you to shut down FAST if you have a large number of small allocations.

    0 讨论(0)
提交回复
热议问题