3

I am creating a process from another process in C# as follows:

process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = "process.exe";
process.OutputDataReceived += ProcessOnOutputDataReceived;

Then in a separate thread I call:

process.Start();
process.BeginOutputReadLine();
process.WaitForExit();

This allows me to have rudimentary IPC between the processes.

I am finding that this process appears to be inheriting an open file handle from the parent process. As a result, the parent process can no longer work with the file.

Is there a way to prevent this from happening? Or is there a way that I can force the child process to release the handle after it has been inherited?

reveazure
  • 653
  • 2
  • 7
  • 14
  • you need use [`UpdateProcThreadAttribute`](https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-updateprocthreadattribute) with `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` for exactly set list of handles which will be inherited (if you need handle inheritance at all). so you need use `CreateProcessW` with `STARTUPINFOEX`, `EXTENDED_STARTUPINFO_PRESENT` flag – RbMm Jan 29 '19 at 22:50
  • 1
    Is there a way to do this with the process object, or any C# code examples for how to do it? – reveazure Jan 29 '19 at 23:09
  • 1
    in *c++* do this not hard, how i know *c#* can declare and call native win api so this is possible from *c#* too, but will be more src code in this case. are this possible with [*Process Class*](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=netframework-4.7.2) can not say exactly, because i dont know and use *c#* but from fast view - almost sure that no - no such functional here – RbMm Jan 29 '19 at 23:14
  • No, not possible with only the `Process` class. You need to P/Invoke `UpdateProcThreadAttribute`; you can use the [`Process.SafeHandle`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.safehandle?view=netframework-4.7.2) or [`Process.Handle`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.handle?view=netframework-4.7.2) properties to get a handle to the process. See [this](https://stackoverflow.com/questions/1427196/net-how-to-pinvoke-updateprocthreadattribute) for a solution. – Christian.K Jan 30 '19 at 05:51
  • OK, that's a start. Can anyone tell me what needs to be in the `lpAttributeList` to still get the stdin/out/err redirect functionality? – reveazure Jan 30 '19 at 16:15

0 Answers0