CloseHandle throwing an exception in Studio 2010 after STDOUT redirection

1

The following code is causing grief when run from Studio 2010 debugger, but seems to run fine from the command line (well, it would because the exception is only thrown in the debugger):

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 );  

A simple CreateFile/CloseHandle sequence works fine, and I have also tried switching the order of the CloseHandle/SetStdHandle calls to no avail, but GetLastError does return 18 (0x12) ERROR_NO_MORE_FILES "There are no more files." if SetStdHandle does run.

Something with the STDOUT redirection is failing, but what?

c++
exception
redirect
stdout
handle
asked on Stack Overflow Dec 17, 2012 by 0xDEADBEEF

1 Answer

0

So, it seems the problem was caused by this section, cunningly hidden by the code's original author:

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

The _close, here commented out, seems to cause the problem.

answered on Stack Overflow Dec 17, 2012 by 0xDEADBEEF

User contributions licensed under CC BY-SA 3.0