今天跟同事讨论一个问题,谈到pthread_create创建线程之后,线程的名字直接从父进程继承下来,但这个名字对我们后续定位分析问题没有直接的帮助,如果能够修改线程的名称,那定位分析问题就比较方便了。
linux下的prctl库自kernel 2.6.9后支持PR_SET_NAME选项,用于设置进程名字,linux的进程一般使用lwp,所以这个函数可以设置线程名字,api定义如下:
#include
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 process name for the calling process, using the value in the location pointed to by (char *) arg2. The name
can be up to 16 bytes long, and should be null-terminated if it contains fewer bytes.
测试程序如下所示:
#include
#include
#include
void* thread1(void* arg)
{
prctl(PR_SET_NAME,"THREAD1");
while(1)
{
printf("thread1\n");
sleep(1000);
}
}
void thread2(void)
{
while(1)
{
printf("thread2\n");
sleep(1000);
}
}
int main()
{
pthread_t th1,th2;
void* retval;
pthread_create(&th1,NULL,thread1,NULL);
pthread_create(&th2,NULL,thread2,NULL);
printf("main thread\n");
pthread_join(&th1,&retval);
pthread_join(&th2,&retval);
}
~
执行测试程序之后,在proc目录下查看线程的名称:
# ps -aux | grep "pthread"
root 14074 0.0 0.0 18640 316 pts/0 Sl+ 15:21 0:00 ./pthread_create
# cat /proc/14074/task/14074/stat
14074 (pthread_create) S 2066 14074 2066 34816 14074 4210688 204 0 0 0 0 0 0 0 20 0 3 0 27940400 19087360 79 4294967295 134512640 134514724 3216437616 3216437328 3078321188 0 0 0 0 3238682441 0 0 17 0 0 0 0 0 0 134520588 134520868 160518144 3216442687 3216442704 3216442704 3216445419 0
# cat /proc/14074/task/14075/stat
14075 (THREAD1) S 2066 14074 2066 34816 14074 4210752 1 0 0 0 0 0 0 0 20 0 3 0 27940400 19087360 79 4294967295 134512640 134514724 3216437616 3076374872 3078321188 0 0 0 0 3238469668 0 0 -1 0 0 0 0 0 0 134520588 134520868 160518144 3216442687 3216442704 3216442704 3216445419 0
线程1已经被修改成THREAD1。