_open_osfhandle
creates a C file descriptor from a windows file handle, and _dup
can change an existing fd's underlying file object. When used to redirect stdout
to a CreatePipe
pipe ReadFile
does not capture output written to stdout
.
The following code snippet demonstrates the core of what I am attempting.
I want to create an anonymous pipe, replacing stdout
so that I can read it from the read handle.
The documentation i've been able to find indicates that _open_osfhandle
and _dup2
can perform this trickery and Microsofts documentation page for dup2 specifically calls out replacing the fd in stdout as being possible.
Given all that, I am expecting the following code to return immediately from ReadFile with the bytes written by printf as prior calls to _write
and fprintf
worked as expected.
HANDLE hread;
HANDLE hwrite;
SECURITY_ATTRIBUTES sa = { sizeof(sa),NULL,TRUE };
CreatePipe(&hread, &hwrite, &sa, 0);
int fd = _open_osfhandle(intptr_t(hwrite), _O_TEXT);
FILE *fp = _fdopen(fd, "w");
setvbuf(fp, NULL, _IONBF, 0);
_dup2(_fileno(fp), _fileno(stdout));
TCHAR buffer[64] = { 0 };
DWORD bytesRead;
//_write(fd, "_write", 6); // works
//fprintf(fp, "fprintf"); // works
printf("printf");
ReadFile(hread, buffer, sizeof(buffer), &bytesRead, NULL);