EDIT: Related post and possible .Net solution: related question (I would like a non-.Net solution)
I have a need to shut-down a child process with a given process ID. My first attempt was to use this code:
bool shutDown(int const processID)
{
// detach handler from 'this', parent process
SetConsoldeCtrlHandler(NULL, TRUE);
// send ctrl-c event to processID
bool success = false;
FreeConsole();
AttachConsole(processID);
success = GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
while(waitUntilSomething()) {}
return success;
}
Now this works fine, however, I would like to return console ctrl to the 'this' process so that if I want to, I can break out of the while loop. With this in mind, I tried this:
bool shutDown(int const processID)
{
// detach handler from 'this' process
SetConsoldeCtrlHandler(NULL, TRUE);
// send ctrl-c event to processID
bool success = false;
FreeConsole();
AttachConsole(processID);
success = GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
SetConsoleCtrlHandler(NULL, FALSE); // <--- I added this bit
while(waitUntilSomething()) {}
return success;
}
But this doesn't work, because the ctrl-c signal then falls through to the parent process and the while loop is never executed.
I also tried the following, using a custom handler to ignore ctrl-c events from 'this':
BOOL WINAPI handler(DWORD eventType)
{
switch(eventType) {
case CTRL_EVENT:
case CTRL_BREAK_EVENT:
return TRUE;
default:
return FALSE;
}
}
bool shutDown(int const processID)
{
// attach custom handler to i
SetConsoldeCtrlHandler(handler, TRUE);
// send ctrl-c event to processID
bool success = false;
FreeConsole();
AttachConsole(processID);
success = GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
SetConsoleCtrlHandler(handler, FALSE);
while(waitUntilSomething()) {}
return success;
}
...but in a similar way to the second example, the ctrl-c then passes straight through to the parent process and the while loop is never executed, because of the second SetConsoleCtrlHandler(handler, FALSE); call.
Is there a way that I can return ctrl-c handling to the parent process after generating a ctrl-c event for a child process, without that event being automatically handled?
Thanks,
Ben.