从Studio 2010调试器运行时,以下代码引起麻烦,但似乎在命令行上运行正常(嗯,这是因为仅在调试器中引发了异常):

HANDLE hCon = GetStdHandle( STD_OUTPUT_HANDLE );  // Preserve STDOUT
HANDLE hFile = CreateFile( pszOutputFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
// At this point hFile = 0x000000d0
// The file is created and has 0 bytes, as expected

// STDOUT is redirected to our new file handle
SetStdHandle( STD_OUTPUT_HANDLE, hFile );

// Do something here that pumps to STDOUT, output is directed to the file correctly
CloseHandle( hFile );  // EXCEPTION here: 0xC0000008: An invalid handle was specified.
SetStdHandle( STD_OUTPUT_HANDLE, hCon );


一个简单的CreateFile / CloseHandle序列可以正常工作,并且我还尝试将CloseHandle / SetStdHandle调用的顺序切换为无效,但是GetLastError确实返回18(0x12)ERROR_NO_MORE_FILES“没有更多文件。”如果SetStdHandle确实运行。

STDOUT重定向失败,但是怎么办?

最佳答案

因此,问题似乎是由代码的原始作者巧妙地隐藏的这一部分引起的:

   int fd = _open_osfhandle( (intptr_t)hFile, O_WRONLY | O_TEXT );
   _dup2( fd, 1 );
//   _close( fd );


_close,这里已注释掉,似乎导致了问题。

09-30 23:04