Reputation: 709
In Windows, when creating a process with CreateProcess
, one can pass true
as the bInheritHandles
argument.
CreateProcess( , , , , bInheritHandles, , , , )
This means that all file handles marked to be inheritable will be, indeed, inherited by the child process.
How can we control whether the underlying file handle created by C++ std::fstream
class is inheritable or not?
Upvotes: 4
Views: 980
Reputation: 595
If you're using fopen
to open the file you can specify the Windows-specific "N"
mode in the fopen
parameters to make the handles not inheritable.
Example:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp = fopen("SomeFile.txt", "rwN");
if (!fp) {
return -1;
}
system("SomeProcess.exe");
fclose(fp);
return 0;
}
Sources:
https://wiki.sei.cmu.edu/confluence/display/c/WIN03-C.+Understand+HANDLE+inheritance
https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen?view=vs-2019
Upvotes: 2
Reputation: 256
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
Upvotes: 3