[VC++/MFC] How can a child process can access a file which is exclusively locked by the Parent Process?

Praveer Kumar 21 Reputation points
2021-09-09T06:12:48.943+00:00

Hi,
Is it possible for a child process to access a file which is exclusively locked by the ParentProcess.

This is how test.txt file has been given the permission
::CreateFile("C\temp\test.txt",
GENERIC_READ | GENERIC_WRITE,
0, // exclusive
NULL, // default security
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
By doing this other process can not open test.txt file. Now I want to create a childProcess and I want only the child process to read "test.txt" file

This is how I am creating the childProcess:
CreateProcess("FileReader.exe",
"C:\temp\test.txt",
&sa,
NULL,
TRUE,
0,
NULL,
NULL,
&si,
&pi)

but it is not able to read the file.

is there anyone who can help me on this ?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,595 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 41,996 Reputation points
    2021-09-09T10:53:10.533+00:00

    Another method is to 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. Don't forget that you 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.


2 additional answers

Sort by: Most helpful
  1. Viorel 113.8K Reputation points
    2021-09-09T10:12:19.49+00:00

    I think that one of the approaches is:

    • The second process is started using CREATE_SUSPENDED parameter.
    • The first process duplicates the handle:   DuplicateHandle( GetCurrentProcess( ), h, pi.hProcess, &h2, 0, TRUE, DUPLICATE_SAME_ACCESS );
      • The first process calls ResumeThread( pi.hThread ) and passes the value of h2 to the second process using some inter-process communication mechanism. In the simplest example, the processes use an intermediate text or binary file that contains the numeric value of h2.

    (Note that the current file position will be the same for both processes).

    0 comments No comments

  2. Praveer Kumar 21 Reputation points
    2021-09-14T04:53:17.027+00:00

    @RLWA32 Thanks For the help. It works now.

    0 comments No comments