-
-
Save code-disaster/44ae4e176feafb0f703810d261c1e1fe to your computer and use it in GitHub Desktop.
Windows Pipe & Process
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
int run_external(const char* command) | |
{ | |
int rval = 1; | |
SECURITY_ATTRIBUTES attr = { | |
.nLength = sizeof(attr), | |
.lpSecurityDescriptor = NULL, | |
.bInheritHandle = TRUE | |
}; | |
HANDLE read_pipe, write_pipe; | |
if (CreatePipe(&read_pipe, &write_pipe, &attr, 0) == 0) | |
{ | |
_E("pipe error\n"); | |
goto e0; | |
} | |
STARTUPINFO si = { | |
.cb = sizeof(si), | |
.dwFlags = STARTF_USESTDHANDLES, | |
.hStdOutput = write_pipe, | |
.hStdError = write_pipe | |
}; | |
PROCESS_INFORMATION pi = {0}; | |
BOOL success = CreateProcess( | |
NULL, | |
(char*) command, | |
NULL, | |
NULL, | |
TRUE, | |
DETACHED_PROCESS, | |
NULL, | |
NULL, | |
&si, | |
&pi | |
); | |
CloseHandle(write_pipe); | |
if (!success) | |
{ | |
_E("can't create process for:\n %s\n", command); | |
goto e1; | |
} | |
char buffer[1024]; | |
bool done = false; | |
while (!done) | |
{ | |
DWORD bytes_read = 0; | |
done = !ReadFile(read_pipe, buffer, sizeof(buffer), &bytes_read, NULL); | |
if (bytes_read > 0) | |
{ | |
/* TODO */ | |
fprintf(stdout, "%s", buffer); | |
fflush(stdout); | |
} | |
} | |
DWORD exit_code = 0; | |
GetExitCodeProcess(pi.hProcess, &exit_code); | |
rval = exit_code; | |
_I("%s returned with error code %d\n", command, rval); | |
CloseHandle(pi.hProcess); | |
CloseHandle(pi.hThread); | |
e1: | |
CloseHandle(read_pipe); | |
//CloseHandle(write_pipe); | |
e0: | |
return rval; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment