Repository navigation
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedarea-System.Diagnostics.Processin-prThere is an active PR which will close this issue when it is merged
Milestone
Description
Background and motivation
There are plenty of ways to create a process where .NET does not support this or where there is already a process handle from native method.
Currently there is no possibility to create a .NET Process object from the SafeProcessHandle.
API Proposal
namespace System.Runtime.InteropServices;
[SupportedOSPlatform("windows")]
public ref struct WindowsProcessStartArguments
{
public WindowsProcessStartArguments();
public unsafe char* Arguments { get; }
public unsafe char* EnvironmentVariables{ get; }
public ProcessStartInfo ProcessStartInfo { get; }
public nint StandardError { get; }
public nint StandardInput { get; }
public nint StandardOutput { get; }
public static Process Start(ProcessStartInfo startInfo, Func<WindowsProcessStartArguments, SafeProcessHandle> callback);
}
[UnsupportedOSPlatform("windows")]
public ref struct UnixProcessStartArguments
{
public UnixProcessStartArguments();
public unsafe byte* ResolvedPath { get; }
public unsafe byte** Arguments { get; }
public unsafe byte** EnvironmentVariables { get; }
public ProcessStartInfo ProcessStartInfo { get; }
public nint StandardError { get; }
public nint StandardInput { get; }
public nint StandardOutput { get; }
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
[UnsupportedOSPlatform("maccatalyst")]
public static Process Start(ProcessStartInfo startInfo, Func<UnixProcessStartArguments, int> callback);
}API Usage
ProcessStartInfo startInfo = new("cmd")
{
ArgumentList = { "/c", "echo hello && echo error 1>&2" },
RedirectStandardOutput = true,
RedirectStandardError = true
};
using Process process = WindowsProcessStartArguments.Start(startInfo, (WindowsProcessStartArguments args) =>
{
Interop.Kernel32.STARTUPINFOEX startupInfoEx = default;
Interop.Kernel32.PROCESS_INFORMATION processInfo = default;
Interop.Kernel32.SECURITY_ATTRIBUTES unused_SecAttrs = default;
startupInfoEx.StartupInfo.cb = sizeof(Interop.Kernel32.STARTUPINFOEX);
startupInfoEx.StartupInfo.hStdInput = args.StandardInput;
startupInfoEx.StartupInfo.hStdOutput = args.StandardOutput;
startupInfoEx.StartupInfo.hStdError = args.StandardError;
startupInfoEx.StartupInfo.dwFlags = Interop.Advapi32.StartupInfoOptions.STARTF_USESTDHANDLES;
bool retVal = Interop.Kernel32.CreateProcess(
null,
args.Arguments,
ref unused_SecAttrs,
ref unused_SecAttrs,
bInheritHandles: true,
Interop.Kernel32.EXTENDED_STARTUPINFO_PRESENT,
args.EnvironmentVariables,
null,
&startupInfoEx,
&processInfo
);
if (!retVal)
{
throw new Win32Exception();
}
Interop.Kernel32.CloseHandle(processInfo.hThread);
return new SafeProcessHandle(processInfo.hProcess, ownsHandle: true);
});Alternative Designs
The alternative design included a ctor, but it was too fragile. Check #128491 for details
Risks
Can't see any as of now, as BCL takes care of removing all known risks before invoking the callback.
Working prototype: #128862
Reacted by Ilya Stupakov
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedarea-System.Diagnostics.Processin-prThere is an active PR which will close this issue when it is merged
Activity
KalleOlaviNiemitalo commentedon Jul 3, 2022
Would this be a Windows-only API? Not clear to me how you'd get a SafeProcessHandle from a native method on Linux or Mac.
AraHaan commentedon Jul 3, 2022
I am sure there is a way yes since they too have process ID's.
DaZombieKiller commentedon Jul 3, 2022
On non-Windows,
Process.SafeHandlewill return a pseudo-SafeProcessHandlewrapping the process ID, but there's no way to get the wrapped process ID from the handle, making the pseudo-handle almost useless since you can't get back to theProcess. I don't think you can get such an instance from a P/Invoke, though I've never tried.fbrosseau commentedon Jul 4, 2022
Modern linux does have proper process file descriptors, but that feature may be too modern for dotnet support (I don't know?). They do solve many problems however - race conditions around PID recycling, etc.
DaZombieKiller commentedon Jul 5, 2022
Thinking about this further, would it make more sense for this to be exposed as a
staticmethod likeGetProcessById?Having a constructor would be consistent with
Socket, but thestaticmethod is more consistent with the other APIs onProcess. It'd also open up the opportunity for theProcessobjects to be cached, though I don't believe they are currently, even forGetProcessById.KalleOlaviNiemitalo commentedon Jul 5, 2022
For creating a Process from a native process handle (SafeProcessHandle or IntPtr) on Windows, I don't think caching would be a good idea. The handle might not have the same access rights as what the Process class specifies when it opens a process handle, and it might have access to a process that the current process is not normally authorised to open. If I created a Process object from such a handle, I would not want that to affect the behaviour of future Process.GetProcessById calls because such an effect would make my app more difficult to test. Also, I would not want Process.Dispose of a different process object to close my process handle prematurely.
Re implementing this on Linux, pidfd_open seems to be the function referenced in #71595 (comment). If I read this correctly, a pidfd does not carry any access rights (if you receive a pidfd, you cannot use that to kill a process that you wouldn't otherwise be authorised to kill).
52 remaining items
AaronRobinsonMSFT commentedon Jun 22, 2026
I'm sorry, but this is a very unhelpful way of answering a question. Can you elaborate a bit. The linked comment is:
What is the
ref structin this case? TheTStateor the API itself? I assume not the API because that is the first argument already. What is "they"? Note also this is in response to a question from the API review that I was not at, so I again I have no idea. The original statement here was from the API feedback, #71595 (comment), which contains "Should we add a TState overload?", what conversation prompted that?AaronRobinsonMSFT commentedon Jun 22, 2026
A namespace is not prior art for this in my opinion. The flags enum,
System.IO.UnixFileMode, is a fair example and mostly aligns with what this API seems to be which is an advanced way of starting a process. That example satisfies any pushback I'd have.bartonjs commentedon Jun 22, 2026
The TState overload is to facilitate passing a ref struct into the callback, as ref structs can't be captured in lambdas... other than cheating and using
IntPtr ptr = &thing. Maybe it's not an important scenario, but that's why it's there.AaronRobinsonMSFT commentedon Jun 22, 2026
So in the hypothetical situation where someone wants a
ref structcaptured by the lambda, we need aTState? It seems like this API has been marked as an advanced API so do we have an actual use case where aref structrepresents a core performance or safety concern? I get the capture idea and as Jan said that is a "Fair" scenario.Personally, I prefer state variables being passed in that is how I imagine most of these types of APIs. My gripe is the fact that there are two ways to do something on an already advanced API that technically can be overcome with some unsafe code for the very few that want it OR every consumer will have state and we should just have the state version.
I'm satisfied with how we got here at this point. The interop team supports this if API review is good with it. Thank you all.
bartonjs commentedon Jun 22, 2026
FWIW: I don't have a particular stake in whether or not we have a
TStatehere, I just wanted to voice a reason for having it so it didn't get discarded out of hand. If that reason is deemed minuscule and the feature group wants to simplify to without it, no worries.Said another way, I don't care what the decision is, just that it's made instead of accidentally defaulted into.
adamsitnik commentedon Jun 23, 2026
@tmds I've updated the prototype (5b63e99) and the proposal to return
pidon Unix.I currently don't see a good reason to have state. If something is conditional (example: run different app for different user), I expect it to be part of the user logic that creates
ProcessStartInfobefore invoking the callback. I've removed it from the proposal. If we ever need it, I am going to create another proposal.bartonjs commentedon Jun 23, 2026
Video
[-][API Proposal]: Process constructor from SafeProcessHandle[/-][+]Add Process.Start callback overload for advanced Interop[/+]Add Process.Start callback overload with WindowsProcessStartArguments…
Add Process.Start callback overload with WindowsProcessStartArguments…