How to Create and Use Anonymous Pipes in .NET

.NET offers easy support for using named pipes, but what about anonymous pipes? Can those be done in .NET? The answer is yes, but it’s tricky to do and only useful in certain situations. You would need several things in order to accomplish this:

A static place where the pipe or collection ofpipes would be stored

A method for knowing when a handle has beencreated

A method for getting the handles in anotherprocess

Assuming we’re not talking about the scenario where Process A always creates Process B where CreateProcess handles the work, the easiest way to implement them would be with a C++/CLI dll. Here’s the steps to make an example implementation in Visual Studio 2013 with comments about what’s happening where in the code:

//Add it to the local collection PipeStore::AddHandles(localHolder.ProcessId, (IntPtr)localHolder.ReadHandle, (IntPtr)localHolder.WriteHandle); return nullptr; //Note the leaks that occur with the way this is currently written as several things aren't closed when they are no longer in use in other parts of the program and in the situations where we return from this function with an exception without cleaning up what we've already made } private: IntPtr hProcess; IntPtr hTarget; //Opens the process tokens void InitializeForProcess(int targetPid) { hProcess = (IntPtr)OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessId()); hTarget = (IntPtr)OpenProcess(PROCESS_ALL_ACCESS, false, targetPid); } };}