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 ?
_open_osfhandle
which is fine to be closed by_close
since your original handle to the same file is still alive.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()._commit
call everything you do with the descriptor? Then why not useFlushFileBuffer
on the handle, or open the file unbuffered, and don't have to worry about this specific problem?