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/...

推荐答案

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                                                                                  

C++相关问答推荐

修改pGM使用指针填充2-D数组但不起作用

InetPton()函数无效的IP地址

如何在C中只使用一个带双方括号([i][j])访问语法的malloc来分配动态大小的2d数组?

丑陋的三重间接:可扩展的缓冲区管理 struct

C编译器是否遵循restrict的正式定义?

ARM64 ASIMD固有的加载uint8_t* 到uint16x8(x3)?

X86/x64上的SIGSEGV,由于原始内存访问和C中的DS寄存器之间的冲突,在Linux上用TCC编译为JIT引擎

函数内的局部字符指针

限制不同类型的限定符

在C++中访问双指针

在移动数组元素时获得意外输出

从C文件中删除注释

类型定义 struct 与简单的类型定义 struct

某些EAX值的不同调用方的CPUID结果不一致

生成的头文件不包括用户定义的文件

如果类型是新的,offsetof是否与typeof一起工作?

为什么 int32_t 和 int16_t 在 printf 输出中具有相同的位数?

C 中 struct 体自赋值是否安全?特别是如果一侧是指向 struct 的指针?

我怎样才能用c语言正常运行这两个进程?

将十六进制值或十进制值分配给 uint16_t 有什么区别?