'How do you send commands from a parent process to run on an existing child cmd.exe process?
I have a piece of code that, amongst other things, creates a child cmd.exe process with redirected I/O handles, given a specific input.
HANDLE child_IN_Rd = NULL;
HANDLE child_IN_Wr = NULL;
HANDLE child_OUT_Rd = NULL;
HANDLE child_OUT_Wr = NULL;
SECURITY_ATTRIBUTES sa;
STARTUPINFOW si;
PROCESS_INFORMATION pi;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
CreatePipe(&child_IN_Rd, &child_IN_Wr, sa, 0);
CreatePipe(&child_OUT_Rd, &child_OUT_Wr, sa, 0);
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdError = child_OUT_Wr;
si.hStdOutput = child_OUT_Wr;
si.hStdInput = child_IN_Rd;
CreateProcessA("C:\\Windows\\system32\\cmd.exe",
NULL,
NULL.
NULL,
false,
NULL,
NULL,
NULL,
si,
pi)
CloseHandle(child_IN_Rd);
CloseHandle(child_OUT_Wr);
The intent is for the code to run cmd commands at the behest of a remote client. The parent receives a string from the client, and writes it to child_IN_Wr. The cmd.exe process should then run the string as a command, and the output is read on the parent console.
Something like this:
WriteFile(child_IN_Wr, command, command_size, NULL, NULL);
...
ReadFile(child_OUT_Rd, buffer, buffer_size, NULL, NULL);
//Do something with the output, eg. print, or sending it back to client.
printf("%s", buffer);
However, I am unable to get it to work. The existing cmd.exe process does not seem to register/process an input written to child_IN_Wr, and no output is read as a result.
I understand that this issue can be easily fixed by simply running CreateProcess with the given command under the CommandLine parameter, every time the parent receives an input from the remote client. However, this spawns and terminates a new cmd.exe process every time a command is run, and I wish to run all the commands on a single cmd.exe process created beforehand given a specific input from a client, that only terminates after the client sends another specific input.
How should I go about this? I have been trying out the use of pipes for IPC, as seen above, but have had no luck thus far. Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
