What exactly is the effect of Ctrl-C on C++ Win32 console applications?

旧街凉风 提交于 2019-12-01 13:55:42

问题


  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?

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/914613/what-exactly-is-the-effect-of-ctrl-c-on-c-win32-console-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!