- Is it possible to handle this event in some way?
- What happens in terms of stack unwinding and deallocation of static/global objects?

- 73,079
- 34
- 148
- 203
3 Answers
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.

- 1,237
- 11
- 17
-
1What about deallocation of statics? – Assaf Lavie May 27 '09 at 11:19
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.

- 278,309
- 50
- 514
- 539
-
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 May 27 '09 at 08:45
-
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 May 27 '09 at 13:46
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.
-
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 May 27 '09 at 11:21
-
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. – May 27 '09 at 11:32
-
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 May 27 '09 at 11:43