문제 설명
control‑c 후 Visual Studio 콘솔 프로그램 충돌 (visual studio console program crashes after control‑c)
Visual Studio 2019의 최신 업데이트(버전 16.5.0 Preview 2.0)를 사용 중이며 control‑c 이벤트를 가로채려고 합니다. 그러나 어떤 이유로 콘솔 프로그램은 항상 내 핸들러를 호출하기 전에 충돌합니다. 그런데 핸들러를 설치하지 않아도 프로그램이 다운됩니다.
컴파일러의 버그일까요? 일반적으로 이와 같은 것을 어떻게 디버깅합니까?
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <cstdint>
uint64_t iterations;
bool running;
BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
{
switch (fdwCtrlType) {
case CTRL_C_EVENT: {
running = false;
return TRUE;
} break;
default: {
return FALSE;
} break;
}
}
int main()
{
if (!SetConsoleCtrlHandler(CtrlHandler, TRUE)) {
std::cout << "Could not install control handler" << std::endl;
}
running = true;
while (running) {
iterations++;
}
std::cout << "Terminated after " << iterations << " iterations." << std::endl;
return 0;
}
참조 솔루션
방법 1:
https://docs.microsoft.com/en‑us/windows/console/setconsolectrlhandler
Here it says that if an application is being debugged, "the system generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger". Hence it isn't chrashing; you can continue excectution and it should work fine. The documentation says:
If the debugger passes the exception on unhandled, CTRL+C is passed to the console process and treated as a signal, as previously discussed.
(by Nowibananatzki、Lukas Thiersch)