Chinaunix首页 | 论坛 | 博客
  • 博客访问: 130451
  • 博文数量: 18
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 174
  • 用 户 组: 普通用户
  • 注册时间: 2014-09-30 10:35
文章分类

全部博文(18)

文章存档

2016年(1)

2015年(13)

2014年(4)

我的朋友

分类: LINUX

2015-10-15 00:31:46

在linux下开发的多线程系统中,如果没有设置新创建的线程的名字,则默认是进程的名字,这导致了每个线程的调试和监控比较麻烦,无法精准定位,为每个线程设置名字则比较好管理和调试。linux下的prctl库自kernel 2.6.9后开始支持PR_SET_NAME和PR_GET_NAME选项用于设置和获取进程名字,linux的线程一般采用lwp(light weight process,轻量级进程)来模拟,所以这个函数可以设置线程名字。

设置完成后可通过如下命令查看:
ps -eL -o pid,user,lwp,comm

API定义如下

  1. int prctl( int option,unsigned long arg2,unsigned long arg3,unsigned long arg4,unsigned long arg5);

  2. PR_SET_NAME (since Linux 2.6.9)
  3. 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.

  4. PR_GET_NAME (since Linux 2.6.11)
  5. Return the process name for the calling process, in the buffer pointed to by (char *) arg2. The buffer should allow space for up to 16 bytes; the returned string will be null-terminated if it is shorter than that.

测试代码

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <sys/prctl.h>
  4.   
  5. void *foo(void *arg)
  6. {
  7.     int idx = arg;
  8.     printf("idx = %d\n", idx);
  9.     switch(idx)
  10.     {
  11.         case 1:
  12.         prctl(PR_SET_NAME, "ThreadName1");
  13.         break;
  14.         case 2:
  15.         prctl(PR_SET_NAME, "ThreadName2");
  16.         break;
  17.         case 3:
  18.         prctl(PR_SET_NAME, "ThreadName3");
  19.         break;
  20.         default:
  21.         break;
  22.     }
  23.   
  24.     sleep(50);
  25.     return 0;
  26. }
  27.   
  28. int main(void)
  29. {
  30.     pthread_t threadIdx[3];
  31.     int threadArgIdx[] = {1, 2, 3};
  32.       
  33.     int i;
  34.     for(i = 0; i < 3; i++)
  35.     {
  36.         pthread_create(threadIdx + i, NULL, foo, (void *)threadArgIdx[i]);
  37.     }
  38.   
  39.     for(i = 0; i < 3; i++)
  40.     {
  41.         pthread_join(threadIdx[i], NULL);
  42.     }
  43.     return 0;
  44. }

参考资料:
http://www.cppblog.com/lxyfirst/archive/2011/03/07/141288.aspx
http://blog.csdn.net/caspiansea/article/details/12073571

阅读(8151) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~