Skip to content

Add Process.Start callback overload for advanced Interop #71595

Closed

Description

@NN---

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

Activity

  1. added
    api-suggestion
    on Jul 3, 2022
  2. ghost added
    untriaged
    on Jul 3, 2022
  3. KalleOlaviNiemitalo commented on Jul 3, 2022

    @KalleOlaviNiemitalo

    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.

  4. AraHaan commented on Jul 3, 2022

    @AraHaan
    Member

    I am sure there is a way yes since they too have process ID's.

  5. DaZombieKiller commented on Jul 3, 2022

    @DaZombieKiller
    Contributor

    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.

    On non-Windows, Process.SafeHandle will return a pseudo-SafeProcessHandle wrapping 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 the Process. I don't think you can get such an instance from a P/Invoke, though I've never tried.

  6. fbrosseau commented on Jul 4, 2022

    @fbrosseau

    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.

    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.

  7. DaZombieKiller commented on Jul 5, 2022

    @DaZombieKiller
    Contributor

    Thinking about this further, would it make more sense for this to be exposed as a static method like GetProcessById?

    using Microsoft.Win32.SafeHandles;
    
    namespace System.Diagnostics;
    
    public partial class Process
    {
        public static Process GetProcessByHandle(SafeProcessHandle handle);
        public static Process GetProcessByHandle(IntPtr handle); // potential extra API
    }

    Having a constructor would be consistent with Socket, but the static method is more consistent with the other APIs on Process. It'd also open up the opportunity for the Process objects to be cached, though I don't believe they are currently, even for GetProcessById.

  8. KalleOlaviNiemitalo commented on Jul 5, 2022

    @KalleOlaviNiemitalo

    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).

  9. added this to the Future milestone on Jul 19, 2022
  10. ghost removed
    untriaged
    on Jul 19, 2022
  11. added
    untriaged
    needs-further-triage
    on Jul 19, 2022
  12. ghost removed
    untriaged
    on Jul 19, 2022
  13. 52 remaining items

  14. AaronRobinsonMSFT commented on Jun 22, 2026

    @AaronRobinsonMSFT
    Member

    I don't fully understand the TState need here. The lambda should be able to capture things. What gain are we looking for in this case? It looks like a C API in an entirely C# sync environment.

    #71595 (comment)

    I'm sorry, but this is a very unhelpful way of answering a question. Can you elaborate a bit. The linked comment is:

    TState is an optimization to avoid GC allocations at the cost of code size.

    Well, it's also the only way to get a ref struct value into the callback, since they can't be captured.

    What is the ref struct in this case? The TState or 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?

  15. AaronRobinsonMSFT commented on Jun 22, 2026

    @AaronRobinsonMSFT
    Member

    there are some namespaces like System.Windows (WPF)

    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.

  16. bartonjs commented on Jun 22, 2026

    @bartonjs
    Member

    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.

  17. AaronRobinsonMSFT commented on Jun 22, 2026

    @AaronRobinsonMSFT
    Member

    The TState overload is to facilitate passing a ref struct into the callback, as ref structs can't be captured in lambdas...

    So in the hypothetical situation where someone wants a ref struct captured by the lambda, we need a TState? It seems like this API has been marked as an advanced API so do we have an actual use case where a ref struct represents 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.

  18. bartonjs commented on Jun 22, 2026

    @bartonjs
    Member

    FWIW: I don't have a particular stake in whether or not we have a TState here, 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.

  19. adamsitnik commented on Jun 23, 2026

    @adamsitnik
    Member

    @tmds I've updated the prototype (5b63e99) and the proposal to return pid on Unix.

    don't have a particular stake in whether or not we have a TState here, 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.

    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 ProcessStartInfo before invoking the callback. I've removed it from the proposal. If we ever need it, I am going to create another proposal.

  20. bartonjs commented on Jun 23, 2026

    @bartonjs
    Member

    Video

    • Changed WindowsProcessStartArguments.Start.callback to return nint instead of SafeProcessHandle, for consistency and safe SafeHandle construction.
    • Moved all of the supported/unsupported annotations to the same location instead of split.
    • We discussed the pointer exposure, and left it as-is since the only use case for these types is P/Invoke
    • System.Runtime.InteropServices seems like the best namespace of ones that exist, and it doesn't seem worthy of a new one.
    namespace System.Runtime.InteropServices;
    
    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; }
    
        [SupportedOSPlatform("windows")]
        public static Process Start(ProcessStartInfo startInfo, Func<WindowsProcessStartArguments, nint> callback);
    }
    
    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("windows")]
        [UnsupportedOSPlatform("ios")]
        [UnsupportedOSPlatform("tvos")]
        [SupportedOSPlatform("maccatalyst")]
        public static Process Start(ProcessStartInfo startInfo, Func<UnixProcessStartArguments, int> callback);
    }
  21. added
    api-approved
    and removed
    api-ready-for-review
    on Jun 23, 2026
  22. changed the title [-][API Proposal]: Process constructor from SafeProcessHandle[/-] [+]Add Process.Start callback overload for advanced Interop[/+] on Jun 29, 2026
  23. added a commit that references this issue on Jun 30, 2026
    e07cdb4
  24. added a commit that references this issue on Jul 15, 2026
    518288d
  25. locked and limited conversation to collaborators on Jul 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Diagnostics.Processin-pr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions