diff --git a/PowerKit.Tests/ProcessExtensionsTests.cs b/PowerKit.Tests/ProcessExtensionsTests.cs new file mode 100644 index 0000000..4ffcf77 --- /dev/null +++ b/PowerKit.Tests/ProcessExtensionsTests.cs @@ -0,0 +1,34 @@ +using System; +using System.Diagnostics; +using System.Threading.Tasks; +using FluentAssertions; +using PowerKit.Extensions; +using Xunit; + +namespace PowerKit.Tests; + +public class ProcessExtensionsTests +{ + [Fact] + public void IsRunning_Running_Test() + { + // Act & assert + Process.IsRunning(Environment.ProcessId).Should().BeTrue(); + } + + [Fact] + public async Task IsRunning_NotRunning_Test() + { + // Arrange + using var process = Process.Start(new ProcessStartInfo("dotnet", "--version") + { + RedirectStandardOutput = true + })!; + + await process.WaitForExitAsync(); + var processId = process.Id; + + // Act & assert + Process.IsRunning(processId).Should().BeFalse(); + } +} diff --git a/PowerKit/Extensions/ProcessExtensions.cs b/PowerKit/Extensions/ProcessExtensions.cs new file mode 100644 index 0000000..292ecf1 --- /dev/null +++ b/PowerKit/Extensions/ProcessExtensions.cs @@ -0,0 +1,25 @@ +using System.Diagnostics; + +namespace PowerKit.Extensions; + +internal static class ProcessExtensions +{ + extension(Process) + { + /// + /// Checks whether the process identified by the specified ID is currently running. + /// + public static bool IsRunning(int processId) + { + try + { + using var process = Process.GetProcessById(processId); + return !process.HasExited; + } + catch + { + return false; + } + } + } +}