views:

832

answers:

3
  1. Is it possible to handle this event in some way?
  2. What happens in terms of stack unwinding and deallocation of static/global objects?
+4  A: 

EDIT: SIGINT, not SIGTERM. And Assaf reports that no objects are destroyed (at least on Windows) for unhanded SIGINT.

The system sends a SIGINT. This concept applies (with some variance) for all C implementations. To handle it, you call signal, specifying a signal handler. See the documentation on the signal function at Open Group and MSDN.

The second question is a little trickier, and may depend on implementation. The best bet is to handle the signal, which allows you to use delete and exit() manually.

Matthew Flaschen
Thanks. fyi, the MSDN page you linked to suggests that the system sends a SIGINT (and that NT upwards does not send SIGTERM at all).
Assaf Lavie
Thanks, Assaf. Corrected.
Matthew Flaschen
Also, SIGINT, which translates into a ExitProcess, does not trigger destruction of any kind of object (global, local static, automatic). If, otoh, you translate the sigint into exit(), globals/statics will be destructor in reverse order of initialization (but automatics not).
Assaf Lavie
+7  A: 

Ctrl-C in console application will generate a signal. The default handler of this signal calls ExitProcess to terminate the application. You can override this behaviour by setting your own handler functions for the signal using SetConsoleCtrlHandler function.

Shino C G
+1 for actually answering the question!
Daniel Earwicker
What about deallocation of statics?
Assaf Lavie
+3  A: 

You can test whether stack unwinding occurs, with some simple code:

#include <iostream>
#include <windows.h>
using namespace std;

struct A {
    ~A() { cerr << "unwound" << endl; }
};

int main() {
    A a;
    while(1) {
     Sleep(1000);
    }
}

Whether it occurs not should be implementation dependant, depending on how the runtime handles the Ctrl-C. In my experience, it does not take place.

anon
Good test! I stand corrected.
Matthew Flaschen
I have a hard time trusting such a test, because I'll never be sure if the behavior will differ for varying project configurations (e.g. libs, dlls, native, managed, multi-threaded and combinations thereof). So I'd rather have the "true" answer and not rely on such a test myself.
Assaf Lavie
There isn't a "true" answer - the C++ Standard has nothing to say on this subject, so what you get will always be implementation dependent.
anon
Well the true answer of VC is enough for me. But I suspect the answer may differ for various project types, as I said.
Assaf Lavie