Skip to content
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

Ensure Process.ProcessName doesn't change when setting Thread.Name on Linux #34064

Merged
merged 11 commits into from
May 12, 2020
7 changes: 7 additions & 0 deletions src/coreclr/src/pal/src/thread/thread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1641,6 +1641,13 @@ CorUnix::InternalSetThreadDescription(

pTargetThread->Lock(pThread);

// Ignore requests to set the main thread name because
tmds marked this conversation as resolved.
Show resolved Hide resolved
// it causes the value returned by Process.ProcessName to change.
if ((pid_t)pTargetThread->GetThreadId() == getpid())
{
goto InternalSetThreadDescriptionExit;
}

/* translate the wide char lpThreadDescription string to multibyte string */
nameSize = WideCharToMultiByte(CP_ACP, 0, lpThreadDescription, -1, NULL, 0, NULL, NULL);

Expand Down
14 changes: 14 additions & 0 deletions src/libraries/System.Threading.Thread/tests/ThreadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,20 @@ public static void NameTest()
});
}

[Fact]
public static void ThreadNameDoesNotAffectProcessName()
lambdageek marked this conversation as resolved.
Show resolved Hide resolved
{
// On Linux, changing the main thread name affects ProcessName.
// To avoid that, .NET ignores requests to change the main thread name.
RemoteExecutor.Invoke(() =>
{
const string ThreadName = "my-thread";
Thread.CurrentThread.Name = ThreadName;
Assert.Equal(ThreadName, Thread.CurrentThread.Name);
Assert.NotEqual(ThreadName, Process.GetCurrentProcess().ProcessName);
}).Dispose();
}

[Fact]
public static void PriorityTest()
{
Expand Down
9 changes: 9 additions & 0 deletions src/mono/mono/utils/mono-threads-posix.c
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,15 @@ mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
if (tid != mono_native_thread_id_get ())
return;

#if defined(__linux__)
/*
* Ignore requests to set the main thread name because
* it causes the value returned by Process.ProcessName to change.
*/
if (tid == (guint64)getpid ())
return;
lambdageek marked this conversation as resolved.
Show resolved Hide resolved
lambdageek marked this conversation as resolved.
Show resolved Hide resolved
#endif

if (!name) {
pthread_setname_np ("");
} else {
Expand Down