在Linux中可以从自身内部更改线程的名称吗?[重复]

问题描述 投票:-1回答:1

从此 回答 我可以看到,这至少在MacOS上是可能的。

我想也许这样就可以了。

pthread_setname_np(pthread_self(), "NEW_NAME");

这不工作,因为 pthread_self() 返回线程ID,而不是一个 pthread_t 数据类型。我找不到一个函数可以返回当前线程的 pthread_t,允许将线程ID转换为 pthread_t 也不允许设置当前名称而不需要提供 pthread_t 数据类型作为参数之一。谢谢。

c linux multithreading pthreads
1个回答
0
投票

好吧。pthread_self() 应该已经返回一个 pthread_t根据pthread文档,所以你展示的代码似乎是正确的。在任何情况下,我都会避免使用 pthread_setname_np() 因为顾名思义,它是不可移植的。

在Linux中,标准的方法是通过 prctl(2):

#include <sys/prctl.h>

int prctl(int option, unsigned long arg2, unsigned long arg3,
            unsigned long arg4, unsigned long arg5);
PR_SET_NAME (since Linux 2.6.9)
       Set the name of the calling thread, using the value in the
       location pointed to by (char *) arg2.  The name can be up to
       16 bytes long, including the terminating null byte.  (If the
       length of the string, including the terminating null byte,
       exceeds 16 bytes, the string is silently truncated.)  This is
       the same attribute that can be set via pthread_setname_np(3)
       and retrieved using pthread_getname_np(3).  The attribute is
       likewise accessible via /proc/self/task/[tid]/comm, where tid
       is the name of the calling thread.

你只需要打电话 prctl()PR_SET_NAME 作为第一个参数,第二个参数是你要设置的名称。

prctl(PR_SET_NAME, "name_here", 0, 0, 0);

请注意,正如手册中所说,名称不能超过16个字节(包括终止符)。

© www.soinside.com 2019 - 2024. All rights reserved.