Skip to content

Instantly share code, notes, and snippets.

@code-disaster

code-disaster/win_pipe.c Secret

Created Jul 26, 2019
Embed
What would you like to do?
Windows Pipe & Process
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