-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Add Process.TryGetProcessById and SafeProcessHandle.TryOpen APIs #128695
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
adamsitnik
merged 8 commits into
copilot/add-safeproceshandle-open-api
from
copilot/add-trygetprocessbyid-methods
May 29, 2026
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
943b669
Add Process.TryGetProcessById and SafeProcessHandle.TryOpen APIs
Copilot e12fb17
Fix test file: add using System.Threading and remove fully-qualified …
Copilot 6528b5e
Address reviewer feedback: delegate Open to TryOpen, pass error code …
Copilot a8bdfff
Dispose Process object in test to avoid resource leak
Copilot ce3c6cb
Address reviewer feedback: UnauthorizedAccessException, simplify Proc…
Copilot 2548a91
Update tests: add UnauthorizedAccessException tests, merge Theory pat…
Copilot 7bb40eb
Merge GetProcessById_KilledProcess_Fails into Open_ExitedProcess_Beha…
Copilot 3600bf1
Apply suggestions from code review
adamsitnik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
211 changes: 211 additions & 0 deletions
211
src/libraries/System.Diagnostics.Process/tests/ProcessOpenTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.ComponentModel; | ||
| using System.Threading; | ||
| using Microsoft.DotNet.RemoteExecutor; | ||
| using Microsoft.Win32.SafeHandles; | ||
| using Xunit; | ||
|
|
||
| namespace System.Diagnostics.Tests | ||
| { | ||
| public class ProcessOpenTests : ProcessTestBase | ||
| { | ||
| [Theory] | ||
| [InlineData(0)] | ||
| [InlineData(-1)] | ||
| public void Open_InvalidProcessId_ThrowsArgumentOutOfRangeException(int processId) | ||
| { | ||
| Assert.Throws<ArgumentOutOfRangeException>(() => SafeProcessHandle.Open(processId)); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(0)] | ||
| [InlineData(-1)] | ||
| public void TryOpen_InvalidProcessId_ThrowsArgumentOutOfRangeException(int processId) | ||
| { | ||
| Assert.Throws<ArgumentOutOfRangeException>(() => SafeProcessHandle.TryOpen(processId, out _)); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(0)] | ||
| [InlineData(-1)] | ||
| public void TryGetProcessById_InvalidProcessId_ThrowsArgumentOutOfRangeException(int processId) | ||
| { | ||
| Assert.Throws<ArgumentOutOfRangeException>(() => Process.TryGetProcessById(processId, out _)); | ||
| } | ||
|
|
||
| [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] | ||
| public void Open_NonExistentProcessId_ThrowsWin32Exception() | ||
| { | ||
| // Use an unlikely process ID that should not exist. | ||
| Assert.Throws<Win32Exception>(() => SafeProcessHandle.Open(int.MaxValue)); | ||
| } | ||
|
|
||
| [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] | ||
| public void TryOpen_NonExistentProcessId_ReturnsFalse() | ||
| { | ||
| bool result = SafeProcessHandle.TryOpen(int.MaxValue, out SafeProcessHandle? handle); | ||
| Assert.False(result); | ||
| Assert.Null(handle); | ||
| } | ||
|
|
||
| [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] | ||
| public void TryGetProcessById_NonExistentProcessId_ReturnsFalse() | ||
| { | ||
| bool result = Process.TryGetProcessById(int.MaxValue, out Process? process); | ||
| Assert.False(result); | ||
| Assert.Null(process); | ||
| } | ||
|
|
||
| [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows), nameof(PlatformDetection.IsNotPrivilegedProcess))] | ||
| public void Open_ProtectedProcess_ThrowsUnauthorizedAccessException() | ||
| { | ||
| int pid = Assert.Single(Process.GetProcessesByName("lsass")).Id; | ||
| Assert.Throws<UnauthorizedAccessException>(() => SafeProcessHandle.Open(pid)); | ||
| } | ||
|
|
||
| [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows), nameof(PlatformDetection.IsNotPrivilegedProcess))] | ||
| public void TryOpen_ProtectedProcess_ThrowsUnauthorizedAccessException() | ||
| { | ||
| int pid = Assert.Single(Process.GetProcessesByName("lsass")).Id; | ||
| Assert.Throws<UnauthorizedAccessException>(() => SafeProcessHandle.TryOpen(pid, out _)); | ||
| } | ||
|
|
||
| [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] | ||
| [InlineData(true)] | ||
| [InlineData(false)] | ||
| public void Open_RunningProcess_ReturnsValidHandle(bool tryOpen) | ||
| { | ||
| using Process process = CreateProcess(static () => | ||
| { | ||
| Thread.Sleep(Timeout.Infinite); | ||
| return RemoteExecutor.SuccessExitCode; | ||
| }); | ||
| process.Start(); | ||
|
|
||
| SafeProcessHandle? handle = null; | ||
| try | ||
| { | ||
| if (tryOpen) | ||
| { | ||
| Assert.True(SafeProcessHandle.TryOpen(process.Id, out handle)); | ||
| } | ||
| else | ||
| { | ||
| handle = SafeProcessHandle.Open(process.Id); | ||
| } | ||
|
|
||
| Assert.False(handle.IsInvalid); | ||
| Assert.Equal(process.Id, handle.ProcessId); | ||
|
adamsitnik marked this conversation as resolved.
|
||
|
|
||
| handle.Kill(); | ||
| Assert.True(handle.TryWaitForExit(TimeSpan.FromMilliseconds(WaitInMS), out _)); | ||
| } | ||
| finally | ||
| { | ||
| process.Kill(); | ||
| process.WaitForExit(); | ||
| handle?.Dispose(); | ||
| } | ||
| } | ||
|
|
||
| [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] | ||
| [InlineData(true)] | ||
| [InlineData(false)] | ||
| public void GetProcessById_RunningProcess_ReturnsProcess(bool tryGet) | ||
| { | ||
| using Process process = CreateProcess(static () => | ||
| { | ||
| Thread.Sleep(Timeout.Infinite); | ||
| return RemoteExecutor.SuccessExitCode; | ||
| }); | ||
| process.Start(); | ||
|
|
||
| Process? found = null; | ||
| try | ||
| { | ||
| if (tryGet) | ||
| { | ||
| Assert.True(Process.TryGetProcessById(process.Id, out found)); | ||
| } | ||
| else | ||
| { | ||
| found = Process.GetProcessById(process.Id); | ||
| } | ||
|
|
||
| Assert.NotNull(found); | ||
| Assert.Equal(process.Id, found.Id); | ||
| Assert.Equal(process.ProcessName, found.ProcessName); | ||
|
|
||
| found.Kill(); | ||
| found.WaitForExit(); | ||
| } | ||
| finally | ||
| { | ||
| process.Kill(); | ||
| process.WaitForExit(); | ||
| found?.Dispose(); | ||
| } | ||
|
adamsitnik marked this conversation as resolved.
|
||
| } | ||
|
|
||
| [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] | ||
| [InlineData(true, true)] | ||
| [InlineData(true, false)] | ||
| [InlineData(false, true)] | ||
| [InlineData(false, false)] | ||
| public void Open_ExitedProcess_BehaviorDependsOnPlatform(bool tryOpen, bool kill) | ||
| { | ||
| using Process process = kill | ||
| ? CreateProcess(static () => { Thread.Sleep(Timeout.Infinite); return RemoteExecutor.SuccessExitCode; }) | ||
| : CreateProcess(static () => RemoteExecutor.SuccessExitCode); | ||
| process.Start(); | ||
|
|
||
| if (kill) | ||
| { | ||
| process.Kill(); | ||
| } | ||
|
|
||
| process.WaitForExit(); | ||
|
|
||
| if (OperatingSystem.IsWindows()) | ||
| { | ||
| SafeProcessHandle? handle = null; | ||
| try | ||
| { | ||
| if (tryOpen) | ||
| { | ||
| Assert.True(SafeProcessHandle.TryOpen(process.Id, out handle)); | ||
| } | ||
| else | ||
| { | ||
| handle = SafeProcessHandle.Open(process.Id); | ||
| } | ||
|
|
||
| // On Windows, the kernel process object persists as long as at least one handle is open. | ||
| Assert.NotNull(handle); | ||
| Assert.False(handle.IsInvalid); | ||
| } | ||
| finally | ||
| { | ||
| handle?.Dispose(); | ||
| } | ||
| } | ||
| else | ||
| { | ||
| // On Unix, once the process has been waited for (reaped), it is removed from the process | ||
| // table and its PID may be reused. | ||
| if (tryOpen) | ||
| { | ||
| bool result = SafeProcessHandle.TryOpen(process.Id, out SafeProcessHandle? handle); | ||
| Assert.False(result); | ||
| Assert.Null(handle); | ||
| } | ||
| else | ||
| { | ||
| Assert.Throws<Win32Exception>(() => SafeProcessHandle.Open(process.Id)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.