linux 设置父进程名称,linux 下设置线程名字

今天跟同事讨论一个问题,谈到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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值