简体   繁体   中英

Inheriting C# Anonymous Pipe Handle in C++ Process

I am trying to inherit a Pipe Handle from a C# parent process to a C++ Child process.

I create the Parent in the C# Process in the following way:

AnonymousPipeServerStream pipe = AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);

string pipeName = pipe.GetClientHandleAsString();

I then pass the handle to the Client Process like this:

ProcessStartInfo clientProcessStartInfo = new ProcessStartInfo("cpp_process.exe", pipeName);
startInfo.UseShellExecute = false;

Process process = new Process {
    StartInfo = startInfo
} 

process.Start();

pipe.DisposeLocalCopyOfClientHandle();

In the Child C++ Process, i get the Pipe Handle like this:

std::string pipeHandleString = argv[1];
int pipeHandleInt = std::stoi(pipeHandleString);

HANDLE pipeHandle = (void*) pipeHandleInt;

But when i try to use the Pipe Handle in the Child Process like this:


std::array<char, 256> buffer = {};

DWORD numberOfBytesRead;

BOOL result = ReadFile(pipeHandle, &buffer, 256, &numberOfBytesRead, nullptr);

Result is FALSE and GetLastError() returns This handle is invalid .

As far as i understand it, the Child Process should inherit the pipe handle automatically?

Removing pipe.DisposeLocalCopyOfClientHandle() does not change the Result.

Also, using the pipe handle in a C# Client Process like this:

AnonymousPipeClientStream pipe = new AnonymousPipeClientStream(PipeDirection.In, args[1]);

Works just fine, so im guessing the C# implementation does something to the Handle that i'm missing in my C++ implementation, but i cant figure out what that is.

The above code works as expected, the problem was outside of the minimum viable example i put together.

I had the pipe handling wrapped in a class. Said class had a destructor that closed the pipe handle. This destructor was running too often, even before the first read from the pipe leading to the invalid handle error.

Commenting out the call to CloseHandle / Preventing the Destrutor from being run when it shouldn't fixed the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM