prctl
理论
// 用 prctl 给线程命名, prctl是个系统调用
#include <sys/prctl.h>
int prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5);
实践
#include <zconf.h>
#include <sys/prctl.h>
#include <stdio.h>
#include <pthread.h>
void* tmain(void *arg)
{
char name[32];
prctl(PR_SET_NAME, (unsigned long)"xx");
prctl(PR_GET_NAME, (unsigned long)name);
printf("%s/n", name);
while (1)
sleep(1);
}
int main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, tmain, NULL);
pthread_join(tid, NULL);
return 0;
}
执行:
$ gcc main.c -l pthread
$ ps aux | grep a.out
oceanst+ 9725 0.0 0.0 14704 384 pts/1 Sl+ 18:52 0:00 ./a.out
$ ps -L -p 9725
PID LWP TTY TIME CMD
9725 9725 pts/1 00:00:00 a.out
9725 9726 pts/1 00:00:00 xx
pthread_setname_np
prctl()只能设置/获取当前线程的名字
在glibc 2.12之后的版本中提供了两个扩展的接口pthread_setname_np()和pthread_getname_np(),可以在进程中设置和读取其他线程的名字。
检查glibc版本:
# getconf GNU_LIBC_VERSION
glibc 2.17
可以使用feature_test_macro_GNU_SOURCE来检查此功能是否可用:
#ifdef _GNU_SOURCE
pthread_setname_np(tid, "someName");
#endif
理论
#include <pthread.h>
/*
* 功能值:该pthread_setname_np()函数设置目标线程的名称。由名称指定的缓冲区必须包含一个长度为15个字符或更少的空终止字符串(不包括NULL)。如果名称长度超过15个字符,则多余的字符将被忽略。如果name为null,则该线程变为未命名
* 返回值:成功返回0
*/
int pthread_setname_np(pthread_t thread, const char *name);
//获取线程名称
int pthread_getname_np(pthread_t thread, char *name);
实践
#define _MULTI_THREADED
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void *threadfunc(void *parm)
{
printf("In the thread.\n");
sleep(45); // allow main program to set the thread name
return NULL;
}
int main(int argc, char **argv)
{
pthread_t thread;
int rc=0;
char theName[16];
memset(theName, 0x00, sizeof(theName));
printf("Create thread using the default attributes\n");
rc = pthread_create(&thread, NULL, threadfunc, NULL);
if(0 == rc)
{
#ifdef _GNU_SOURCE
rc = pthread_setname_np(thread, "THREADNAMEISTOOLONG");
sleep(10);
if(0 == rc)
{
rc = pthread_getname_np(thread, theName);
if(0 == rc)
{
printf("The thread name is %s.\n", theName);
}
}
#endif
rc = pthread_join(thread, NULL);
}
if(0 != rc)
{
printf("An error occurred - %d\n", rc);
}
printf("Main completed\n");
return(rc);
}