NTDLS NTDLS - 1 year ago 97
C Question

Redirecting console (or stdout) to named pipe no longer works when compiling with Visual Studio 2015

I have a scripting engine which redirects its stdout to a named pipe for debugging purposes. The code below has been working since Visual Studio 6, but no longer seems to work at all when compiling with VS2015. No errors are thrown, but the output continues to be written to the console instead of the named pipe. When I compile this application in VS2012, it works as expected.

hNamedPipe is the pipe I want to redirect console text to.

int hCrt = _open_osfhandle((intptr_t)hNamedPipe, _O_TEXT);
FILE *hf = _fdopen(hCrt, "w");
*stdout = *hf;
setvbuf(stdout, NULL, _IONBF, 0);

How might I redirect stdio to a named pipe when compiling with the Visual C++ v14 platform tool-set?

Answer Source

Thanks to James McNellis I was able to arrive at a solution:

This is by design. FILE is an opaque data type; you are not allowed to dereference a FILE as you have done in your code.

This is the code which ultimately worked for me:

void main()
    RedirectIO(stdio, hNamedPipe);
    printf("Hello World."); //This arrived at the listening named pipe.

void RedirectIO(FILE *hFrom, HANDLE hTo)
    int fd = _open_osfhandle((intptr_t)hTo, _O_WRONLY | _O_TEXT);
    _dup2(fd, _fileno(hFrom));
    setvbuf(hFrom, NULL, _IONBF, 0); /Disable buffering.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download