How to name a thread in Linux?
Solution 1
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)
Solution 2
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.
Marbal
Updated on July 09, 2022Comments
-
Marbal almost 2 years
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?
-
Marbal almost 13 yearsRelated question: stackoverflow.com/questions/5026531/…
-
Alexis Wilke almost 3 yearsSomehow the
prctl()
(andpthread_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: stackoverflow.com/questions/68676407/…
-
-
Marbal about 15 yearsThat 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.
-
Fusspawn about 15 yearsGlad it worked, I wasnt sure if it was even the right Constant for it, :)
-
Marbal almost 15 yearsFurther investigation shows that busybox's "top" and "ps" don't report thread names. You need the full versions from the "procps" package.
-
Sam Liao about 13 yearsyou can force "ps" to show that name with the c switch (ps Hcx for example).
-
Nemo over 12 yearsOn Linux it's called
pthread_setname_np
and it was added in glibc 2.11.2. -
Mikhail T. over 11 yearsThis is, probably, the most-detailed answer on the subject.
-
Hi-Angel about 9 years@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.