Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

c++ - Handle CTRL+C on Win32

I have some problems with the handling of CTRL+C events, in a Win32 C++ console program.

Basically my program looks like this: (based on this other question: Windows Ctrl-C - Cleaning up local stack objects in command line app)

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;
}

The problem is the cleanup code not being executed at all.

After the execution of the handler function the process is terminated, but without execute the code after the main loop. What's wrong?

EDIT: as requested, this is a minimal test case similar to my program: http://pastebin.com/6rLK6BU2

I don't get the "test cleanup-instruction" string in my output.

I don't know if this is important, I'm compiling with MinGW.


EDIT 2: The problem with the test case program is the use of the Sleep() function. Without it the program works as expected.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following code works for me:

#include <windows.h> 
#include <stdio.h> 

BOOL WINAPI consoleHandler(DWORD signal) {

    if (signal == CTRL_C_EVENT)
        printf("Ctrl-C handled
"); // do cleanup

    return TRUE;
}

int main()
{
    running = TRUE;
    if (!SetConsoleCtrlHandler(consoleHandler, TRUE)) {
        printf("
ERROR: Could not set control handler"); 
        return 1;
    }

    while (1) { /* do work */ }

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...