The C runtime creates inheritable handles by default.
ofstream outFile("filename.txt") ;
CreateProcess("program.exe", ..., true, ...) ; //program.exe will inherit the above file handle
So, if you want a handle to be inherited, you don't need to do anything.
If you DO NOT want a handle to be inherited, you have to set the handle's HANDLE_FLAG_INHERIT
flag yourself using WinAPI function SetHandleInformation
, like this:
FILE* filePtr = fopen("filename.txt", "w") ;
SetHandleInformation( (HANDLE)_get_osfhandle(_fileno(filePtr)), HANDLE_FLAG_INHERIT, 0) ;
ofstream outFile(filePtr) ;
In the third line, above, the constructor ofstream(FILE*)
is an extension to the standard that exists in Visual Studio (I don't know about other compilers).
After that constructor, filePtr
is now owned by outFile
, so calling outFile.close()
closes filePtr
as well. You can completely forget about the filePtr
variable.
Documentation: fopen, _fileno, _get_osfhandle, SetHandleInformation