How to name a thread in Linux? [duplicate]
Asked Answered
D

2

43

I have a multithreaded Linux application written in C/C++. I have chosen names for my threads. To aid debugging, I would like these names to be visible in GDB, "top", etc. Is this possible, and if so how?

(There are plenty of reasons to know the thread name. Right now I want to know which thread is taking up 50% CPU (as reported by 'top'). And when debugging I often need to switch to a different thread - currently I have to do "thread apply all bt" then look through pages of backtrace output to find the right thread).

The Windows solution is here; what's the Linux one?

Dynast answered 22/4, 2009 at 16:21 Comment(2)
Related question: #5027031Dynast
Somehow the prctl() (and pthread_setname_np() did not work for me. It changed the name of ALL my threads. So rather useless. Instead I had to write the name to the comm file. See: #68676907Leoleod
D
45

Posix Threads?

This evidently won't compile, but it will give you an idea of where to go hunting. I'm not even sure its the right PR_ command, but i think it is. It's been a while...

  #include <sys/prctl.h>
  prctl(PR_SET_NAME,"<null> terminated string",0,0,0)
Dominus answered 22/4, 2009 at 16:32 Comment(6)
That worked, thanks! The documentation says PR_SET_NAME sets the process name; but that documentation is wrong - it does actually set the thread name. Now "top" and "ps -L" show the thread name.Dynast
Glad it worked, I wasnt sure if it was even the right Constant for it, :)Dominus
I've always identified threads based on the start function as shown in the thread's stack-trace. Nice to know there's a clean alternative.Olivette
Further investigation shows that busybox's "top" and "ps" don't report thread names. You need the full versions from the "procps" package.Dynast
you can force "ps" to show that name with the c switch (ps Hcx for example).Vitebsk
@arsane not the busybox's one. Busybox tools are very limited, sometimes have a different args. And e.g. its free just give wrong results.Hyperventilation
P
14

If you are using a library like ACE the Thread has a way to specify the thread name when creating a new thread.

BSD Unix has also a pthread_set_name_np call.

Otherwise you can use prctl as mentioned by Fusspawn.

Posterior answered 22/4, 2009 at 16:57 Comment(2)
On Linux it's called pthread_setname_np and it was added in glibc 2.11.2.Reborn
This is, probably, the most-detailed answer on the subject.Deplore

© 2022 - 2024 — McMap. All rights reserved.