How to set the name of a thread in Linux pthreads?

c, linux, pthreads

Solution

Use the `prctl(2)` function with the option `PR_SET_NAME` (see the docs).

Note that old versions of the docs are a bit confusing. They say

Set the process name for the calling process

but since threads are light weight processes (LWP) on Linux, one thread is one process in this case.

You can see the thread name with `ps -o cmd` or with:

cat /proc/$PID/task/$TID/comm

or in between the `()` of `cat /proc/$PID/task/$TID/stat`:

4223 (kjournald) S 1 1 1 0...

or from GDB `info threads` between double quotes:

* 1    Thread 0x7ffff7fc7700 (LWP 6575) "kjournald" 0x00007ffff78bc30d in nanosleep () at ../sysdeps/unix/syscall-template.S:84                                                                                  

Problem

Is there any way of setting the name of a thread in Linux? My main purpose is it would be helpful while debugging, and also nice if that name was exposed through e.g. `/proc/$PID/task/$TID/...`

Original source

Related problems