I have a Parent process which creates a file using CreateFile()
and locks it. below is the code:
m_hWriterLockFile = ::CreateFile("C:\\Test.txt",
GENERIC_READ | GENERIC_WRITE,
0, // exclusive
NULL, // default security
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
Now, I want only the child process to access this locked file. I do not want any other process to read this file.
I have created a child process. Below is the sample code:
// Initialize a security attributes structure.
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = TRUE;
if (!CreateProcess("FileReader.exe", // I want to invoke this exe
"C:\\Test.txt",
&sa,
NULL,
TRUE,
0,
NULL,
NULL,
&si,
&pi))
{
std::cout << "Create Process Faild (%d) " << GetLastError() << '\n';
}
Unfortunately, I am not able to achieve my goal, is there anyone who can help me? Is there any other way to achieve this? I will share more information(code) if needed.
Note: I didn't share the complete code to make the post shorter.
CodePudding user response:
Here is the answer of of my question :
create the file with an inheritable handle and pass that handle to the child process. A simple way to do this is to pass it as a command line parameter. We must pass a SECURITY_ATTRIBUTES structure that specifies TRUE for bInheritHandle to CreateFile and also pass TRUE to the bInheritHandles parameter of the call to CreateProcess.
Create File
Ex:
SECURITY_ATTRIBUTES sa{ sizeof sa, nullptr, TRUE };
HANDLE hFile = CreateFileA("C:\\Test.txt",
GENERIC_READ | GENERIC_WRITE,
0,
&sa,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
Child Process:
UINT_PTR uiHandle = reinterpret_cast<UINT_PTR>(hFile);
sprintf_s(szCmdLine, "\"%s\" %Iu", szExePath, uiHandle);
if (CreateProcessA(nullptr,
szCmdLine,
nullptr,
nullptr,
TRUE,
CREATE_NEW_CONSOLE,
nullptr,
nullptr,
&si,
&pi))
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}