| 9 | #include <io.h> |
| 10 | |
| 11 | int common_pipe::open(const std::string& cmd, char mode) |
| 12 | { |
| 13 | if (opened()) |
| 14 | close(); // prevent resource leak |
| 15 | HANDLE hChildStdinRd, hChildStdinWr, hStdin, hStdout; |
| 16 | SECURITY_ATTRIBUTES saAttr{}; |
| 17 | // Set up security attributes for inheritable handles |
| 18 | saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); |
| 19 | saAttr.bInheritHandle = TRUE; |
| 20 | saAttr.lpSecurityDescriptor = NULL; |
| 21 | |
| 22 | // Create a pipe for the child process's input |
| 23 | if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) |
| 24 | return report(GetLastError(), "CreatePipe"); |
| 25 | |
| 26 | // Ensure the write handle to the pipe is not inherited by child |
| 27 | // processes |
| 28 | if (!SetHandleInformation(hChildStdinWr, HANDLE_FLAG_INHERIT, 0)) { |
| 29 | auto err = GetLastError(); |
| 30 | CloseHandle(hChildStdinRd); |
| 31 | return report(err, "SetHandleInformation(hChildStdinWr)"); |
| 32 | } |
| 33 | |
| 34 | // Create a pipe for the child process's output |
| 35 | if (!CreatePipe(&hStdin, &hStdout, &saAttr, 0)) { |
| 36 | auto err = GetLastError(); |
| 37 | CloseHandle(hChildStdinRd); |
| 38 | CloseHandle(hChildStdinWr); |
| 39 | return report(err, "CreatePipe"); |
| 40 | } |
| 41 | |
| 42 | // Ensure the read handle to the output pipe is not inherited by child |
| 43 | // processes |
| 44 | if (!SetHandleInformation(hStdout, HANDLE_FLAG_INHERIT, 0)) { |
| 45 | auto err = GetLastError(); |
| 46 | CloseHandle(hChildStdinRd); |
| 47 | CloseHandle(hChildStdinWr); |
| 48 | CloseHandle(hStdin); |
| 49 | return report(err, "SetHandleInformation(hStdout)"); |
| 50 | } |
| 51 | |
| 52 | // Configure STARTUPINFO structure for the new process |
| 53 | STARTUPINFO si{}; |
| 54 | ZeroMemory(&si, sizeof(STARTUPINFO)); |
| 55 | si.cb = sizeof(STARTUPINFO); |
| 56 | si.hStdError = hStdout; |
| 57 | si.hStdOutput = hStdout; |
| 58 | si.hStdInput = hChildStdinRd; |
| 59 | si.dwFlags |= STARTF_USESTDHANDLES; |
| 60 | PROCESS_INFORMATION pi; |
| 61 | |
| 62 | // Create the child process, while hiding the window |
| 63 | if (!CreateProcess(NULL, const_cast<char *>(cmd.c_str()), NULL, NULL, TRUE, |
| 64 | CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) { |
| 65 | auto err = GetLastError(); |
| 66 | CloseHandle(hChildStdinRd); |
| 67 | CloseHandle(hChildStdinWr); |
| 68 | CloseHandle(hStdin); |
no outgoing calls
no test coverage detected