-
-
Save garyng2000/840b64c0c0ac941ca984a7858c61072a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdlib.h> // NULL | |
| #include <stdbool.h> // false | |
| #include <windows.h> // AttachConsole, CTRL_C_EVENT, etc. | |
| #include <stdio.h> // printf | |
| #include <strsafe.h> | |
| void logLastError() | |
| { | |
| LPTSTR errorText = NULL; | |
| FormatMessage( | |
| // use system message tables to retrieve error text | |
| FORMAT_MESSAGE_FROM_SYSTEM | |
| // allocate buffer on local heap for error text | |
| |FORMAT_MESSAGE_ALLOCATE_BUFFER | |
| // Important! will fail otherwise, since we're not | |
| // (and CANNOT) pass insertion parameters | |
| |FORMAT_MESSAGE_IGNORE_INSERTS, | |
| NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM | |
| GetLastError(), | |
| MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), | |
| (LPTSTR)&errorText, // output | |
| 0, // minimum size for output buffer | |
| NULL); // arguments - see note | |
| if ( NULL != errorText ) | |
| { | |
| printf("failure: %s", errorText); | |
| LocalFree(errorText); | |
| errorText = NULL; | |
| } | |
| } | |
| void sendCtrlC(int pid) | |
| { | |
| //This does not require the console window to be visible. | |
| printf("sending ctrl+c to pid %d", pid); // have to log here or we'll be sending it to the other console with printf [!] XXX could maybe duplicate descriptors first or some odd...oh well. | |
| FreeConsole(); // free current console, in case we're being run from a cmd.exe otherwise can't attach to another (at most one). And we probably are...if it fails because we don't have one, that's OK too. | |
| if (AttachConsole(pid)) | |
| { | |
| // Disable Ctrl-C handling for our own program, so we don't "kill" ourselves on accident... | |
| SetConsoleCtrlHandler(NULL, true); | |
| GenerateConsoleCtrlEvent(CTRL_C_EVENT , 0); // these get sent to every process attached to this console, FWIW... | |
| // could also send CTRL_BREAK_EVENT | |
| // TODO could wait here for process to exit, hard kill it (TerminateProcess) after a pause (pause info: http://stackoverflow.com/a/31020562/32453) | |
| } | |
| else { | |
| logLastError(); | |
| } | |
| } | |
| int main( int argc, const char* argv[] ) { | |
| // assume they know the pid... | |
| if (argc != 2) { | |
| printf("syntax: pid"); | |
| return 1; | |
| } | |
| int pid = atoi(argv[1]); | |
| sendCtrlC(pid); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment