How to gracefully terminate a process?

后端 未结 6 1698
深忆病人
深忆病人 2020-11-30 03:14

I want to terminate a number of processes, but I want to give each process the chance to save its data, ask the user about saving a file and even ignore the close request.

相关标签:
6条回答
  • 2020-11-30 03:29

    Use the EndTask API function. It is the same function that is used by task manager.

    BOOL EndTask(      
        HWND hWnd,
        BOOL fShutDown,
        BOOL fForce
    );
    

    http://msdn.microsoft.com/en-us/library/ms633492(VS.85).aspx

    0 讨论(0)
  • 2020-11-30 03:38

    You can use taskkill /im your_program.exe to send a termination signal to the application. It will trigger a WM_CLOSE to windows message queue. You can use Either https://msdn.microsoft.com/en-us/library/windows/desktop/ms633573(v=vs.85).aspx or

    https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getmessage

    to process the message.

    Please refer a similar answer Win32 API analog of sending/catching SIGTERM

    0 讨论(0)
  • 2020-11-30 03:39

    To add to Chris Becke answer about terminating gracefully terminating console process.

    AttachConsole() to attach to the console application and send control break event, similar to that of pressing CTRL+C in command prompt.

    Using GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT,processID).

    This control event should be handled in console application for graceful termination.

    0 讨论(0)
  • 2020-11-30 03:45

    See MSKB Q178893 How To Terminate an Application "Cleanly" in Win32. Basically send send WM_CLOSE to all windows of the target app to allow a grace shutdown, before force kill the app with TerminateProcess

    0 讨论(0)
  • 2020-11-30 03:50

    I'm not too sure about the win32 apis but you could shell execute the taskkill command line function.

    taskkill /?
    taskkill /pid 1230
    taskkill /im notepad.exe
    

    The /f switch would force the kill but not using it just sends the termination signal so the application closes gracefully.

    0 讨论(0)
  • 2020-11-30 03:53

    EnumWindows enumerates all the top level windows in a process. GetWindowThreadProcessId gets the process and Id of each thread.

    You now have enough information to gracefully close any GUI application.

    You can send WM_CLOSE messages to any window you wish to close. Many windows handle WM_CLOSE to prompt the user to save documents.You can send a WM_QUIT message using PostThreadMessage to the discovered threads to cause the message loop to terminate.

    User code is not allowed to call DestroyWindow from a different app or thread to the windows... if the app does not respond to WM_CLOSE or WM_QUIT requests you're back in TerminateProcess land.

    This will not close console applications as the application process, and process that owns the window, are different.


    Refer to T.s. Arun's answer below for the correct method for dealing with console applications.

    0 讨论(0)
提交回复
热议问题