-
-
Save z4none/c274cc5a72d779c881444d15959b02ad to your computer and use it in GitHub Desktop.
This file contains 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 <Windows.h> | |
#include <iostream> | |
#include <thread> | |
struct pipe | |
{ | |
pipe() | |
{ | |
SECURITY_ATTRIBUTES sa = { sizeof(sa), nullptr,true}; | |
CreatePipe(&read, &write, &sa, 0); | |
} | |
~pipe() | |
{ | |
if(read) CloseHandle(read); | |
if(write) CloseHandle(write); | |
} | |
void closeRead() | |
{ | |
CloseHandle(read); | |
read=nullptr; | |
} | |
void closeWrite() | |
{ | |
CloseHandle(write); | |
write=nullptr; | |
} | |
HANDLE read {nullptr}; | |
HANDLE write{nullptr}; | |
}; | |
struct processInfo : public PROCESS_INFORMATION | |
{ | |
processInfo() : PROCESS_INFORMATION{} | |
{ | |
} | |
~processInfo() | |
{ | |
if(hProcess) CloseHandle(hProcess); | |
if(hThread) CloseHandle(hThread); | |
} | |
}; | |
struct startupInfo : public STARTUPINFO | |
{ | |
startupInfo() : STARTUPINFO{sizeof STARTUPINFO} | |
{} | |
}; | |
void reader(HANDLE stdout_pipe) | |
{ | |
DWORD br; | |
char output[256]{}; | |
while(ReadFile(stdout_pipe, output, 255, &br, nullptr)) | |
{ | |
output[br]='\0'; | |
std::cout << output; | |
} | |
} | |
int main(void) | |
{ | |
pipe stdinPipe; | |
pipe stdoutPipe; | |
pipe stderrPipe; | |
std::thread stdoutReader{::reader,stdoutPipe.read}; // read from the read end of the stdout pipe | |
std::thread stderrReader{::reader,stderrPipe.read}; | |
char cmdline[] = R"(findstr /i hello c:\temp\*.txt)"; | |
processInfo pi; | |
startupInfo si; | |
si.dwFlags = STARTF_USESTDHANDLES; | |
si.hStdInput = stdinPipe.read; | |
si.hStdOutput = stdoutPipe.write; // give the the write end of the stdout pipe to the child so it can write to it. | |
si.hStdError = stderrPipe.write; | |
CreateProcess(nullptr, cmdline, nullptr, nullptr, true, 0, nullptr, nullptr, &si, &pi); | |
// new process has now inherited these handles. Close our copy, so we can detect when the child closes their copy. | |
stdinPipe.closeRead(); | |
stdoutPipe.closeWrite(); | |
stderrPipe.closeWrite(); | |
stdoutReader.join(); | |
stderrReader.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment