title: Handle CTRL+C on Win32
body: <p>I have some problems with the handling of <kbd>CTRL</kbd>+<kbd>C</kbd> events, in a <em>Win32 C++</em> console program.</p>
  
  <p>Basically my program looks like this: (based on this other question: <a href="https://stackoverflow.com/questions/7475115/windows-ctrl-c-cleaning-up-local-stack-objects-in-command-line-app">Windows Ctrl-C - Cleaning up local stack objects in command line app</a>)</p>
  
  <pre><code>bool running;
  
  int main() {
  
      running = true;
      SetConsoleCtrlHandler((PHANDLER_ROUTINE) consoleHandler, TRUE);
  
      while (running) {
         // do work
         ...
      }
  
      // do cleanup
      ...
  
      return 0;
  }
  
  bool consoleHandler(int signal) {
  
      if (signal == CTRL_C_EVENT) {
  
          running = false;
      }
      return true;
  }
  </code></pre>
  
  <p>The problem is the cleanup code not being executed at all. </p>
  
  <p>After the execution of the handler function the process is terminated, but without execute the code after the main loop. What's wrong?</p>
  
  <p>EDIT: as requested, this is a minimal test case similar to my program: <a href="http://pastebin.com/6rLK6BU2" rel="noreferrer">http://pastebin.com/6rLK6BU2</a></p>
  
  <p>I don't get the "test cleanup-instruction" string in my output.</p>
  
  <p>I don't know if this is important, I'm compiling with <em>MinGW</em>.</p>
  
  <hr>
  
  <p>EDIT 2: The problem with the test case program is the use of the <code>Sleep()</code> function. Without it the program works as expected. </p>
  
  <p>In Win32 the function handler runs in another thread, so when the handler/thread ends its execution the main thread is sleeping. Probably this is the cause of process interruption?</p>