Im trying to print the output and input of cmd commands recieved to stdout just like a normal cmd.exe would do.
I could use the function _popen
but when i start a program like Python or Powershell whith it, it doesnt work. So i Need the Output of the child process and be able to send commands to the child process.
there is a simmilar question here
So i modified the code from this link to look like this:
void WriteToPipe(char* command){
DWORD dwRead, dwWritten;
BOOL bSuccess = FALSE;
bSuccess = WriteFile(g_hChildStd_IN_Wr, command, strlen(command), &dwWritten, NULL);
// Close the pipe handle so the child process stops reading.
if (!CloseHandle(g_hChildStd_IN_Wr))
ErrorExit(TEXT("StdInWr CloseHandle"));
}
void ReadFromPipe(void){
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
bSuccess = ReadFile(g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
bSuccess = WriteFile(hParentStdOut, chBuf, dwRead, &dwWritten, NULL);
//bSuccess = PeekNamedPipe(g_hChildStd_OUT_Rd, NULL, BUFSIZE, &dwRead, &dwTotalAvailBytes, &dwBytesLeft);
}
the main loop looks like this:
CreateChildProcess("C:\\Python27\\python.exe");
char input_buffer[100] = { 0 };
while (1){
fgets(input_buffer, 99, stdin);
WriteToPipe(input_buffer);
ReadFromPipe();
}
everything else (from the code) stayed the same.
Now my Problem is, i want to enter multiple commands to the same process, but there is a CloseHandle fucntion in WriteToPipe, after the handle is closed i cant enter more commands.
How to get a valid HANDLE to write more than 1 command to the process ?
close the handle in main() function since g_hChildStd_IN_Wr is global. also,
return bSuccess;
notify you if write to pipe has succeededput ReadFromPipe() in a separate Thread; my code here is a garbage but it is working code, it is for test purpose only.