diff --git a/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.Unix.cs b/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.Unix.cs deleted file mode 100644 index 64df4e7a1c421e..00000000000000 --- a/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.Unix.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace System.Diagnostics -{ - internal static partial class TraceListenerHelpers - { - internal static int GetProcessId() - { - // Whereas the Win32 implementation caches the GetProcessId result, the Unix - // implementation doesn't so as to avoid problems with fork'd child processes - // ending up returning the same id as the parent. - return Interop.Sys.GetPid(); - } - - internal static string GetProcessName() - { - if (s_processName == null) - { - using (var process = Process.GetCurrentProcess()) - { - s_processName = process.ProcessName; - } - } - - return s_processName; - } - } -} diff --git a/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.Windows.cs b/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.Windows.cs deleted file mode 100644 index 682f714c250f71..00000000000000 --- a/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.Windows.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace System.Diagnostics -{ - internal static partial class TraceListenerHelpers - { - private static volatile bool s_hasProcessId; - private static volatile int s_processId; - - internal static int GetProcessId() - { - if (!s_hasProcessId) - { - s_processId = (int)Interop.Kernel32.GetCurrentProcessId(); - s_hasProcessId = true; - } - - return s_processId; - } - - internal static string GetProcessName() - { - - if (s_processName == null) - { - using (var process = Process.GetCurrentProcess()) - { - s_processName = process.ProcessName; - } - } - - return s_processName; - } - } -} diff --git a/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.cs b/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.cs deleted file mode 100644 index 2d9c689e8337a9..00000000000000 --- a/src/libraries/Common/src/System/Diagnostics/TraceListenerHelpers.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#nullable enable -namespace System.Diagnostics -{ - internal static partial class TraceListenerHelpers - { - private static volatile string? s_processName; - - internal static int GetThreadId() - { - return Environment.CurrentManagedThreadId; - } - } -} diff --git a/src/libraries/System.Console/tests/CancelKeyPress.Unix.cs b/src/libraries/System.Console/tests/CancelKeyPress.Unix.cs index fddb0f0126c064..7d0f008cf37e31 100644 --- a/src/libraries/System.Console/tests/CancelKeyPress.Unix.cs +++ b/src/libraries/System.Console/tests/CancelKeyPress.Unix.cs @@ -60,7 +60,7 @@ public void ExitDetectionNotBlockedByHandler() }; // Generate CancelKeyPress - Assert.Equal(0, kill(Process.GetCurrentProcess().Id, SIGINT)); + Assert.Equal(0, kill(Environment.ProcessId, SIGINT)); // Wait till we block CancelKeyPress Assert.True(tcs.Task.Wait(WaitFailTestTimeoutSeconds * 1000)); @@ -100,7 +100,7 @@ private void HandlerInvokedForSignal(int signalOuter) try { int signalInner = int.Parse(signalStr); - Assert.Equal(0, kill(Process.GetCurrentProcess().Id, signalInner)); + Assert.Equal(0, kill(Environment.ProcessId, signalInner)); Assert.True(tcs.Task.Wait(WaitFailTestTimeoutSeconds * 1000)); Assert.Equal( signalInner == SIGINT ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak, diff --git a/src/libraries/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj b/src/libraries/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj index b42fd17bfeb23a..c7165ca014e56a 100644 --- a/src/libraries/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj +++ b/src/libraries/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj @@ -152,8 +152,6 @@ Link="Common\Interop\Windows\Advapi32\Interop.AdjustTokenPrivileges.cs" /> - - Gets the path to the current executable, or null if it could not be retrieved. private static string? GetExePath() { - return Interop.Process.GetProcPath(Interop.Sys.GetPid()); + return Interop.Process.GetProcPath(Environment.ProcessId); } // ---------------------------------- diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs index e22245033b8fae..cab74e4ebcf47f 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs @@ -94,7 +94,7 @@ private int ParentProcessId /// Gets the path to the current executable, or null if it could not be retrieved. private static string GetExePath() { - return Interop.libproc.proc_pidpath(Interop.Sys.GetPid()); + return Interop.libproc.proc_pidpath(Environment.ProcessId); } // ---------------------------------- @@ -103,7 +103,7 @@ private static string GetExePath() private Interop.libproc.rusage_info_v3 GetCurrentProcessRUsage() { - return Interop.libproc.proc_pid_rusage(Interop.Sys.GetPid()); + return Interop.libproc.proc_pid_rusage(Environment.ProcessId); } } } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs index b13a42c8cdae26..131912f5729f95 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs @@ -305,12 +305,6 @@ private ProcessPriorityClass PriorityClassCore } } - /// Gets the ID of the current process. - private static int GetCurrentProcessId() - { - return Interop.Sys.GetPid(); - } - /// Checks whether the argument is a direct child of this process. private bool IsParentOf(Process possibleChildProcess) => Id == possibleChildProcess.ParentProcessId; diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs index 520ab528cc7f37..34e17620dca79e 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs @@ -367,12 +367,6 @@ private IntPtr ProcessorAffinityCore } } - /// Gets the ID of the current process. - private static int GetCurrentProcessId() - { - return unchecked((int)Interop.Kernel32.GetCurrentProcessId()); - } - /// /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs index 8f802cbc539afa..e47cac99ac8127 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs @@ -1069,7 +1069,7 @@ public static Process[] GetProcesses(string machineName) /// public static Process GetCurrentProcess() { - return new Process(".", false, GetCurrentProcessId(), null); + return new Process(".", false, Environment.ProcessId, null); } /// diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs index 49d3194b1edc9c..38512ded55f871 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs @@ -96,7 +96,7 @@ private static ProcessModuleCollection GetModules(int processId, bool firstModul SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { - hCurProcess = ProcessManager.OpenProcess((int)Interop.Kernel32.GetCurrentProcessId(), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true); + hCurProcess = ProcessManager.OpenProcess(Environment.ProcessId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true); if (!Interop.Kernel32.IsWow64Process(hCurProcess, out bool sourceProcessIsWow64)) { diff --git a/src/libraries/System.Diagnostics.Process/tests/Interop.Unix.cs b/src/libraries/System.Diagnostics.Process/tests/Interop.Unix.cs index 71883ef35f374a..5cc19a03f9b825 100644 --- a/src/libraries/System.Diagnostics.Process/tests/Interop.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/tests/Interop.Unix.cs @@ -10,9 +10,6 @@ namespace System.Diagnostics.Tests { internal partial class Interop { - [DllImport("libc")] - internal static extern int getpid(); - [DllImport("libc")] internal static extern int getsid(int pid); } diff --git a/src/libraries/System.Diagnostics.Process/tests/Interop.cs b/src/libraries/System.Diagnostics.Process/tests/Interop.cs index d10e65e516e901..e7388724a38999 100644 --- a/src/libraries/System.Diagnostics.Process/tests/Interop.cs +++ b/src/libraries/System.Diagnostics.Process/tests/Interop.cs @@ -54,9 +54,6 @@ public struct SID_AND_ATTRIBUTES [DllImport("kernel32.dll")] public static extern bool GetProcessWorkingSetSizeEx(SafeProcessHandle hProcess, out IntPtr lpMinimumWorkingSetSize, out IntPtr lpMaximumWorkingSetSize, out uint flags); - [DllImport("kernel32.dll")] - internal static extern int GetCurrentProcessId(); - [DllImport("kernel32.dll")] internal static extern bool ProcessIdToSessionId(uint dwProcessId, out uint pSessionId); diff --git a/src/libraries/System.Diagnostics.Process/tests/ProcessTests.cs b/src/libraries/System.Diagnostics.Process/tests/ProcessTests.cs index ef50d90e429c80..ca9a3f6dbacef5 100644 --- a/src/libraries/System.Diagnostics.Process/tests/ProcessTests.cs +++ b/src/libraries/System.Diagnostics.Process/tests/ProcessTests.cs @@ -408,11 +408,20 @@ public void StartTime_GetNotStarted_ThrowsInvalidOperationException() Assert.Throws(() => process.StartTime); } + [Fact] + public void GetCurrentProcess_Id_EqualsCurrentProcessId() + { + using Process current = Process.GetCurrentProcess(); + Assert.Equal(Environment.ProcessId, current.Id); + } + [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void TestId() { CreateDefaultProcess(); + Assert.NotEqual(Environment.ProcessId, _process.Id); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle)); @@ -1050,12 +1059,7 @@ public void TestGetCurrentProcess() Process current = Process.GetCurrentProcess(); Assert.NotNull(current); - int currentProcessId = -#if TargetsWindows - Interop.GetCurrentProcessId(); -#else - Interop.getpid(); -#endif + int currentProcessId = Environment.ProcessId; Assert.Equal(currentProcessId, current.Id); } diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System.Diagnostics.TextWriterTraceListener.csproj b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System.Diagnostics.TextWriterTraceListener.csproj index 41a5392d92c42e..ee094ea301e8b3 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System.Diagnostics.TextWriterTraceListener.csproj +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System.Diagnostics.TextWriterTraceListener.csproj @@ -10,24 +10,6 @@ - - - - - - - - - - - diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs index 26b68395ef2601..cf38c8d8539567 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/XmlWriterTraceListener.cs @@ -15,6 +15,7 @@ public class XmlWriterTraceListener : TextWriterTraceListener { private const string FixedHeader = ""; + private static volatile string? s_processName; private readonly string _machineName = Environment.MachineName; private StringBuilder? _strBldr; private XmlTextWriter? _xmlBlobWriter; @@ -254,14 +255,21 @@ private void WriteStartHeader(string source, TraceEventType eventType, int id, T [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] private void WriteEndHeader() { + string? processName = s_processName; + if (processName is null) + { + using Process process = Process.GetCurrentProcess(); + s_processName = processName = process.ProcessName; + } + InternalWrite("\" />"); InternalWrite(""); InternalWrite(""); diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/tests/XmlWriterTraceListenerTests.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/tests/XmlWriterTraceListenerTests.cs index e55b6c98f37404..efcfb6f8a5638c 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/tests/XmlWriterTraceListenerTests.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/tests/XmlWriterTraceListenerTests.cs @@ -102,12 +102,9 @@ public void ListenerWithFilter() { // Ensure we use an arbitrary ID that doesn't match the process ID or thread ID. int traceTransferId = 1; - using (Process p = Process.GetCurrentProcess()) + while (traceTransferId == Environment.ProcessId || traceTransferId == Environment.CurrentManagedThreadId) { - while (traceTransferId == p.Id || traceTransferId == Environment.CurrentManagedThreadId) - { - traceTransferId++; - } + traceTransferId++; } string file = GetTestFilePath(); diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System.Diagnostics.TraceSource.csproj b/src/libraries/System.Diagnostics.TraceSource/src/System.Diagnostics.TraceSource.csproj index c556e70f03a633..b13f7ff9528db5 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System.Diagnostics.TraceSource.csproj +++ b/src/libraries/System.Diagnostics.TraceSource/src/System.Diagnostics.TraceSource.csproj @@ -27,35 +27,15 @@ - - - - - - - - - - - - - diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs index d377f7432c76b5..cdc431dfe527db 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs @@ -29,7 +29,7 @@ public int ProcessId { get { - return TraceListenerHelpers.GetProcessId(); + return Environment.ProcessId; } } @@ -37,7 +37,7 @@ public string ThreadId { get { - return TraceListenerHelpers.GetThreadId().ToString(CultureInfo.InvariantCulture); + return Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture); } } diff --git a/src/libraries/System.Diagnostics.TraceSource/tests/TraceEventCacheClassTests.cs b/src/libraries/System.Diagnostics.TraceSource/tests/TraceEventCacheClassTests.cs index 28749857bc0173..6933d0323daee2 100644 --- a/src/libraries/System.Diagnostics.TraceSource/tests/TraceEventCacheClassTests.cs +++ b/src/libraries/System.Diagnostics.TraceSource/tests/TraceEventCacheClassTests.cs @@ -24,8 +24,8 @@ public void DateTimePropertyTest() public void ProcessIdTest() { var cache = new TraceEventCache(); - var id = cache.ProcessId; - var expected = System.Diagnostics.Process.GetCurrentProcess().Id; + int id = cache.ProcessId; + int expected = Environment.ProcessId; Assert.Equal((int)expected, id); } diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/CreateSocketTests.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/CreateSocketTests.cs index d490777c4d0c93..cf21032d91fcd1 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/CreateSocketTests.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/CreateSocketTests.cs @@ -570,10 +570,10 @@ public unsafe void Ctor_SafeHandle_UnknownSocket_Success() { Assert.Equal(AddressFamily.Unknown, netlink.AddressFamily); - netlink.Bind(new NlEndPoint(Process.GetCurrentProcess().Id)); + netlink.Bind(new NlEndPoint(Environment.ProcessId)); nl_request req = default; - req.nlh.nlmsg_pid = (uint)Process.GetCurrentProcess().Id; + req.nlh.nlmsg_pid = (uint)Environment.ProcessId; req.nlh.nlmsg_type = RTM_GETROUTE; /* We wish to get routes */ req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; req.nlh.nlmsg_len = sizeof(nl_request); diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/SocketDuplicationTests.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/SocketDuplicationTests.cs index 17cf3bbff10bd0..2acd34cca39c39 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/SocketDuplicationTests.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/SocketDuplicationTests.cs @@ -27,14 +27,6 @@ public class SocketDuplicationTests private static string GetMessageString(ArraySegment data, int count) => Encoding.ASCII.GetString(data.AsSpan().Slice(0, count)); - private static readonly Lazy s_currentProcessId = new Lazy(() => - { - using var process = Process.GetCurrentProcess(); - return process.Id; - }, LazyThreadSafetyMode.PublicationOnly); - - private static int CurrentProcessId => s_currentProcessId.Value; - [Fact] public void UseOnlyOverlappedIO_AlwaysFalse() { @@ -62,7 +54,7 @@ public void DuplicateAndClose_WhenDisposed_Throws() Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Dispose(); - Assert.Throws(() => socket.DuplicateAndClose(CurrentProcessId)); + Assert.Throws(() => socket.DuplicateAndClose(Environment.ProcessId)); } [PlatformSpecific(TestPlatforms.Windows)] @@ -77,7 +69,7 @@ public void BlockingState_IsTransferred(bool blocking) }; Assert.Equal(blocking, original.Blocking); - SocketInformation info = original.DuplicateAndClose(CurrentProcessId); + SocketInformation info = original.DuplicateAndClose(Environment.ProcessId); using Socket clone = new Socket(info); Assert.Equal(blocking, clone.Blocking); @@ -112,7 +104,7 @@ public void SocketCtr_SocketInformation_Unix_ThrowsPlatformNotSupportedException public void DuplicateAndClose_Unix_ThrowsPlatformNotSupportedException() { using Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - int processId = CurrentProcessId; + int processId = Environment.ProcessId; Assert.Throws(() => socket.DuplicateAndClose(processId)); } @@ -127,11 +119,11 @@ public async Task DuplicateAndClose_TcpClient() using Socket client0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - using Socket client1 = new Socket(client0.DuplicateAndClose(CurrentProcessId)); + using Socket client1 = new Socket(client0.DuplicateAndClose(Environment.ProcessId)); Assert.False(client1.Connected); client1.Connect(listener.LocalEndPoint); - using Socket client2 = new Socket(client1.DuplicateAndClose(CurrentProcessId)); + using Socket client2 = new Socket(client1.DuplicateAndClose(Environment.ProcessId)); Assert.True(client2.Connected); using Socket handler = await listener.AcceptAsync(); @@ -151,7 +143,7 @@ public async Task DuplicateAndClose_TcpListener() listener0.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener0.Listen(1); - using Socket listener1 = new Socket(listener0.DuplicateAndClose(CurrentProcessId)); + using Socket listener1 = new Socket(listener0.DuplicateAndClose(Environment.ProcessId)); using Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(listener1.LocalEndPoint); @@ -182,7 +174,7 @@ static void RunTest() listenerProto.Listen(1); EndPoint ep = listenerProto.LocalEndPoint; - using Socket listenerDuplicate = new Socket(listenerProto.DuplicateAndClose(CurrentProcessId)); + using Socket listenerDuplicate = new Socket(listenerProto.DuplicateAndClose(Environment.ProcessId)); using var serverPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable); @@ -228,7 +220,7 @@ public async Task DoAsyncOperation_OnBothOriginalAndClone_ThrowsInvalidOperation await originalServer.ReceiveAsync(_receiveBuffer, SocketFlags.None); - SocketInformation info = originalServer.DuplicateAndClose(CurrentProcessId); + SocketInformation info = originalServer.DuplicateAndClose(Environment.ProcessId); using Socket cloneServer = new Socket(info); await Assert.ThrowsAsync(() => @@ -243,7 +235,7 @@ public void SocketCtr_SocketInformation_NonIpSocket_ThrowsNotSupportedException( if (!Socket.OSSupportsUnixDomainSockets) return; using Socket original = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); - SocketInformation info = original.DuplicateAndClose(CurrentProcessId); + SocketInformation info = original.DuplicateAndClose(Environment.ProcessId); Assert.ThrowsAny(() => _ = new Socket(info)); } @@ -331,7 +323,7 @@ public async Task DuplicateAndClose_TcpServerHandler(AddressFamily addressFamily if (sameProcess) { Task handlerCode = Task.Run(() => HandlerServerCode(_ipcPipeName)); - RunCommonHostLogic(CurrentProcessId); + RunCommonHostLogic(Environment.ProcessId); await handlerCode; } else diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index 739a0315d2bbe0..a5422abee6b597 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -1604,7 +1604,6 @@ - @@ -1814,7 +1813,6 @@ - diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs index 31bd3353929892..273d04bae8a180 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs @@ -60,6 +60,8 @@ public static string MachineName } } + private static int GetCurrentProcessId() => Interop.Sys.GetPid(); + internal const string NewLineConst = "\n"; public static string SystemDirectory => GetFolderPathCore(SpecialFolder.System, SpecialFolderOption.None); diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Windows.cs index ac98739689d95f..751747b96593c6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Windows.cs @@ -86,6 +86,8 @@ private static string ExpandEnvironmentVariablesCore(string name) Interop.Kernel32.GetComputerName() ?? throw new InvalidOperationException(SR.InvalidOperation_ComputerName); + private static int GetCurrentProcessId() => unchecked((int)Interop.Kernel32.GetCurrentProcessId()); + private static unsafe OperatingSystem GetOSVersion() { if (Interop.NtDll.RtlGetVersionEx(out Interop.NtDll.RTL_OSVERSIONINFOEX osvi) != 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.cs index f287b7e21dc124..c971a015164987 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.cs @@ -117,6 +117,24 @@ public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption opt return GetFolderPathCore(folder, option); } + private static int s_processId; + private static volatile bool s_haveProcessId; + + /// Gets the unique identifier for the current process. + public static int ProcessId + { + get + { + if (!s_haveProcessId) + { + s_processId = GetCurrentProcessId(); + s_haveProcessId = true; + } + + return s_processId; + } + } + public static bool Is64BitProcess => IntPtr.Size == 8; public static bool Is64BitOperatingSystem => Is64BitProcess || Is64BitOperatingSystemWhen32BitProcess; diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.Unix.cs deleted file mode 100644 index c4ed0a995dc01d..00000000000000 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.Unix.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace System.Runtime.Versioning -{ - public static partial class VersioningHelper - { - private static int GetCurrentProcessId() => Interop.Sys.GetPid(); - } -} diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.Windows.cs deleted file mode 100644 index aa876d72b2a9e7..00000000000000 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.Windows.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace System.Runtime.Versioning -{ - public static partial class VersioningHelper - { - private static int GetCurrentProcessId() => unchecked((int)Interop.Kernel32.GetCurrentProcessId()); - } -} diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.cs index 7a4363f538b1ba..b552a4ce1292c1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/VersioningHelper.cs @@ -50,7 +50,7 @@ public static string MakeVersionSafeName(string? name, ResourceScope from, Resou { safeName.Append(separator); safeName.Append('p'); - safeName.Append(GetCurrentProcessId()); + safeName.Append(Environment.ProcessId); } if ((requires & SxSRequirements.CLRInstanceID) != 0) { diff --git a/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs b/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs index 86cffe4caa30f1..19bd4cd730ce84 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs @@ -60,6 +60,20 @@ public void CurrentManagedThreadId_Idempotent() Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId); } + [Fact] + public void ProcessId_Idempotent() + { + Assert.InRange(Environment.ProcessId, 1, int.MaxValue); + Assert.Equal(Environment.ProcessId, Environment.ProcessId); + } + + [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + public void ProcessId_MatchesExpectedValue() + { + using RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => Console.WriteLine(Environment.ProcessId), new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }); + Assert.Equal(handle.Process.Id, int.Parse(handle.Process.StandardOutput.ReadToEnd())); + } + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void CurrentManagedThreadId_DifferentForActiveThreads() { diff --git a/src/libraries/System.Runtime/ref/System.Runtime.cs b/src/libraries/System.Runtime/ref/System.Runtime.cs index 4d7086384cca32..80a78a047d14e8 100644 --- a/src/libraries/System.Runtime/ref/System.Runtime.cs +++ b/src/libraries/System.Runtime/ref/System.Runtime.cs @@ -1869,6 +1869,7 @@ public static partial class Environment public static string MachineName { get { throw null; } } public static string NewLine { get { throw null; } } public static System.OperatingSystem OSVersion { get { throw null; } } + public static int ProcessId { get { throw null; } } public static int ProcessorCount { get { throw null; } } public static string StackTrace { get { throw null; } } public static string SystemDirectory { get { throw null; } }