简体   繁体   English

动态分配的控制台I / O的Visual Studio 2015问题

[英]Visual Studio 2015 Issues with dynamically allocated console I/O

I have recently upgraded a project to VS2015. 我最近将一个项目升级到VS2015。 The application is a Windows executable based on some platform independent libraries which are using stdout, stderr. 该应用程序是Windows可执行文件,它基于一些使用stdout,stderr的平台无关的库。 These are redirected by the application to separate pipes used in separate threads which forward the messages to the debugger, syslog, file or to the console (which is dynamically allocated on Windows) according to user options. 应用程序将它们重定向到单独线程中使用的单独管道,这些单独管道根据用户选项将消息转发到调试器,syslog,文件或控制台(在Windows上动态分配)。

The problem is that the new CRT in VC2015 does not support stdio redirection the usual way: 问题在于,VC2015中的新CRT不支持通常的stdio重定向:

FILE *fp = _fdopen(new_stdout_handle, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);

Examining CRT source, the only way to redirect stdout indeed is freopen, which is good to redirect stdout to file or to CONOUT$ but not to pipe. 检查CRT源,重定向stdout的唯一方法的确是freopen,这是将stdout重定向到文件或CONOUT $而不是管道的好方法。 _dup2 is also not a solution because the internal file handle of stdout and stderr are both set to -2 in Windows executables. _dup2也不是解决方案,因为Windows可执行文件中stdout和stderr的内部文件句柄都设置为-2。 So, it seems there is no way to redirect stdout, stderr to pipe any more. 因此,似乎没有办法将stdout,stderr重定向到管道。

Does anybody has a clue, how to redirect stdout, stderr to pipe? 有人知道如何将stdout,stderr重定向到管道吗? Any comment is appreciated. 任何评论表示赞赏。

I have had this issue after moving to VS 2015. The solution is to use the WriteFile() function. 移至VS 2015后遇到了此问题。解决方案是使用WriteFile()函数。 This redirects output to stdout. 这会将输出重定向到stdout。 Replace the code all around _open_osfhandle() and _fdopen() with WriteFile(). 用WriteFile()替换_open_osfhandle()和_fdopen()周围的代码。 Here an example 这是一个例子

HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdout != INVALID_HANDLE_VALUE)
{
   DWORD dwWritten;
   char buf[32];
   sprintf(buf, " WOW! I have been redirected to stdout!");
   long len = (long)strlen(buf);
   BOOL bSuccess = WriteFile(hStdout, buf, len, &dwWritten, NULL);
  //if bSuccess = 1, then you succeeded!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM