3
HANDLE h = CreateFile( ... );
//...
int fd = _open_osfhandle( reinterpret_cast<intptr_t>(h), 0 );
_commit( fd );

// _close(); // Not required

According to MSDN

The _close function closes the file associated with fd. The file descriptor and the underlying OS file handle are closed. Thus, it is not necessary to call CloseHandle if the file was originally opened using the Win32 function CreateFile and converted to a file descriptor using _open_osfhandle.

So according to the documentation, if I call _close() the underlying file HANDLE (my file) will close too, which is something that I don't want.

But I don't think this answers how I handle the file descriptor returned by _open_osfhandle and what happens to it. Is it ok if I just ignore the file descriptor and wait until the file is closed later ? Will file clean up (CloseHandle()) destroy the file descriptor too ?

3
  • 2
    Sounds like you need DuplicateHandle to pass a duplicate to _open_osfhandle which is fine to be closed by _close since your original handle to the same file is still alive.
    – CherryDT
    Commented May 4, 2016 at 10:51
  • In the windows API a HANDLE represents a reference to a kernel object (such as a file). If you want to have multiple references to a single object, you simply create multiple HANDLEs. e.g. via DuplicateHandle. This gives you a handle, to close at your leisure - and a handle to give to _open_ofshandle, to be closed by a balanced call to _close(). Commented May 4, 2016 at 10:55
  • 1
    If the _commit call everything you do with the descriptor? Then why not use FlushFileBuffer on the handle, or open the file unbuffered, and don't have to worry about this specific problem? Commented May 4, 2016 at 10:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.