使用prctl为线程命名

使用prctl的PR_SET_NAME选项功能可以为线程命名,测试代码如下:

#include <stdio.h>
#include <pthread.h>
#include <sys/prctl.h>
#include <unistd.h>

void *func1(void *arg)
{
    prctl(PR_SET_NAME, "func1");
    pause();
}

void *func2(void *arg)
{
    prctl(PR_SET_NAME, "func2");
    pause();
}

int main()
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, func1, NULL);
    pthread_create(&tid2, NULL, func2, NULL);
    
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
}

代码很简单,启动程序后,可以通过top -Hp pid 查看该程序的状态,可以看到输出如下:


  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                                                        
45731 xxxxx     20   0 26712  504  388 S  0.0  0.0   0:00.00 prctl                                                                                                                           
45733 xxxxx     20   0 26712  504  388 S  0.0  0.0   0:00.00 func1                                                                                                                           
45734 xxxxx     20   0 26712  504  388 S  0.0  0.0   0:00.00 func2          

在top的输出中,有三个线程,其中有两个的名字是通过prctl设置的。在/proc/pid/task/tid/目录下的stat文件和status文件,也可以看到相应的名字,方便查看线程状态。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值