Can I send a ctrl-C (SIGINT) to an application on Windows?

前端 未结 17 2721
甜味超标
甜味超标 2020-11-22 09:15

I have (in the past) written cross-platform (Windows/Unix) applications which, when started from the command line, handled a user-typed Ctrl-C combinat

17条回答
  •  一向
    一向 (楼主)
    2020-11-22 10:02

    Here is the code I use in my C++ app.

    Positive points :

    • Works from console app
    • Works from Windows service
    • No delay required
    • Does not close the current app

    Negative points :

    • The main console is lost and a new one is created (see FreeConsole)
    • The console switching give strange results...

    // Inspired from http://stackoverflow.com/a/15281070/1529139
    // and http://stackoverflow.com/q/40059902/1529139
    bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
    {
        bool success = false;
        DWORD thisConsoleId = GetCurrentProcessId();
        // Leave current console if it exists
        // (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
        bool consoleDetached = (FreeConsole() != FALSE);
    
        if (AttachConsole(dwProcessId) != FALSE)
        {
            // Add a fake Ctrl-C handler for avoid instant kill is this console
            // WARNING: do not revert it or current program will be also killed
            SetConsoleCtrlHandler(nullptr, true);
            success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
            FreeConsole();
        }
    
        if (consoleDetached)
        {
            // Create a new console if previous was deleted by OS
            if (AttachConsole(thisConsoleId) == FALSE)
            {
                int errorCode = GetLastError();
                if (errorCode == 31) // 31=ERROR_GEN_FAILURE
                {
                    AllocConsole();
                }
            }
        }
        return success;
    }
    

    Usage example :

    DWORD dwProcessId = ...;
    if (signalCtrl(dwProcessId, CTRL_C_EVENT))
    {
        cout << "Signal sent" << endl;
    }
    

提交回复
热议问题