Run arbitrary subprocesses on Windows and still terminate cleanly?

旧时模样 提交于 2019-11-28 07:37:17

I guess I'm a bit late on this question but I'll write something anyway for anyone having the same problem.

My problem is similar in that I'd like my application to be a GUI application but the processes executed should be run in the background without any interactive console window attached.

I managed to solve this using GenerateConsoleCtrlEvent(). The tricky part is just that the documentation is not really clear on exactly how it can be used and the pitfalls with it.

My solution is based on what is described here. But that didn't really explain all the details either, so here is the details on how to get it working.

  1. Create a new helper application "Helper.exe". This application will sit between your application (parent) and the child process you want to be able to close. It will also create the actual child process. You must have this "middle man" process or GenerateConsoleCtrlEvent() will fail.

  2. Use some kind of IPC mechanism to communicate from the parent to the helper process that the helper should close the child process. When the helper get this event it calls "GenerateConsoleCtrlEvent(CTRL_BREAK, 0)" which closes down itself and the child process. I used an event object for this myself which the parent completes when it wants to cancel the child process.

To create your Helper.exe create it with CREATE_NO_WINDOW and CREATE_NEW_PROCESS_GROUP. And when creating the child process create it with no flags (0) meaning it will derive the console from its parent. Failing to do this will cause it to ignore the event.

It is very important that each step is done like this. I've been trying all different kinds of combinations but this combination is the only one that works. You can't send a CTRL_C event. It will return success but will be ignored by the process. CTRL_BREAK is the only one that works. Doesn't really matter since they will both call ExitProcess() in the end.

You also can't call GenerateConsoleCtrlEvent() with a process groupd id of the child process id directly allowing the helper process to continue living. This will fail as well.

I spent a whole day trying to get this working. This solution works for me but if anyone has anything else to add please do. I went all other the net finding lots of people with similar problems but no definite solution to the problem. How GenerateConsoleCtrlEvent() works is also a bit weird so if anyone knows more details on it please share.

As @Shakta said GenerateConsoleCtrlEvent() is very tricky, but you can send Ctrl+C without helper process.

void SendControlC(int pid)
{
    AttachConsole(pid); // attach to process console
    SetConsoleCtrlHandler(NULL, TRUE); // disable Control+C handling for our app
    GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // generate Control+C event
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!