Linux下,查看进程中创建的线程名称和线程数量的方法

在分析Linux问题时,经常要查看进程的相关信息,但要进一步深入剖析时,就需要查看进程下的各线程的情况。

先说下,如何了解一个进程到底开启了多少线程?

先用ps名称查看当前运行的进程

然后根据pid查看当前进程运行了多少线程,以进程pid=275为例

~ # cat /proc/275/status
Name: fui.app
State: S (sleeping)
Tgid: 275
Pid: 275
PPid: 162
TracerPid: 0
Uid: 0 0 0 0
Gid: 0 0 0 0
FDSize: 256
Groups:
VmPeak: 270228 kB
VmSize: 148136 kB
VmLck: 0 kB
VmHWM: 15896 kB
VmRSS: 15888 kB
VmData: 116332 kB
VmStk: 84 kB
VmExe: 920 kB
VmLib: 25932 kB
VmPTE: 272 kB
Threads: 23 #这里表示总共运行了23个线程
SigQ: 6/2048
SigPnd: 00000000000000000000000000000000
ShdPnd: 00000000000000000000000000000000
SigBlk: 00000000000000000000000000000000
SigIgn: 00000000000000000000000000000006
SigCgt: 00000000000000000000000380211608
CapInh: 0000000000000000
CapPrm: fffffffffffffeff
CapEff: fffffffffffffeff
CapBnd: fffffffffffffeff
voluntary_ctxt_switches: 20805
nonvoluntary_ctxt_switches: 7897

查看当前275进程的的线程id:

ls /proc/275/task
275 303 306 497 517 568 570 572 576 578 580 632
302 304 398 498 567 569 571 575 577 579 631

这些线程id如何和代码中的线程一一对应呢?这就要用到prctl函数在写代码的时候就设置好线程名称,举个栗子:

#include
#include
#include

void* thread1(void* arg)
{

prctl(PR_SET_NAME,"THREAD1");
while(1)
{
printf("thread1\n");
sleep(1000);
}
}

int main()
{
pthread_t th1;
void* retval;
pthread_create(&th1,NULL,thread1,NULL);
printf("main thread\n");
pthread_join(&th1,&retval);
}

这样就能和线程对应了,比如303 (THREAD1) 括号中就是线程名称,注意名称不要超过15个字符:

cat /proc/275/task/303/stat
303 (THREAD1) S 162 150 150 0 -1 4194368 21 41023 0 32 0 0 121 433 20 0 23 0 841 275992576 3972 2147483647 4194304 5132756 2144749904 885821040 738429592 0 0 6 2168328 2147810444 0 0 -1 0 0 0 0 0 0

Posted in 未分类