用prctl给线程命名

对于多线程应用程序,如果能够给每个线程命名,那么调试起来的便利是不言而喻的。
今天看LWN上的周报,看到有人正在给prctl添加给进程内其它线程命名的接口,并从中得知,给线程自身命名的接口已经存在,不由窃喜,遂写下以下验证代码:

#include
#include
#include
void* tmain(void *arg)
{
char name[32]; 
prctl(PR_SET_NAME, (unsigned long)"xx"); 
prctl(PR_GET_NAME, (unsigned long)name);
printf("%s/n", name);
while (1)
sleep(1);
}
int main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, tmain, NULL);
pthread_join(tid, NULL);
return 0;
}

编译并运行:

xiaosuo@gentux test $ gcc t_threadname.c -l pthread
xiaosuo@gentux test $ ./a.out
xx

在另一个终端,通过ps找到a.out的pid:

xiaosuo@gentux test $ ps aux | grep a.out
xiaosuo  29882  0.0  0.0  14144   544 pts/6    Sl+  16:23   0:00 ./a.out

看命名是否奏效:

xiaosuo@gentux test $ cd /proc/29882/task/
xiaosuo@gentux task $ ls
29882  29883
xiaosuo@gentux task $ cd 29883/
xiaosuo@gentux 29883 $ cat cmdline
./a.outxiaosuo@gentux 29883 $

有点儿郁闷,cmdline显示的竟然还是./a.out。通过运行时打印的xx和strace检查prctl的返回值确认prctl确实成功运行。怀疑这个名字只能通过prctl获得,有点儿失落,可心仍不甘。查看ps的man,并实验,终于找到了"xx":

xiaosuo@gentux 29883 $ ps -L -p 29882
  PID   LWP TTY          TIME CMD
29882 29882 pts/6    00:00:00 a.out
29882 29883 pts/6    00:00:00 xx

strace后知道这个“xx”竟然隐匿于stat和status:

xiaosuo@gentux 29883 $ cat stat                                               
29883 (xx) S 7168 29882 7168 34822 29882 4202560 11 0 0 0 2 0 0 0 20 0 2 0 28515372 14483456 136 18446744073709551615 4194304 4196620 140735304261728 18446744073709551615 140435890519585 0 0 0 0 18446744071564503939 0 0 -1 1 0 0 0 0 0      
xiaosuo@gentux 29883 $ cat status                                               
Name:   xx                                                                      
State:  S (sleeping)                                                            
Tgid:   29882                                                                   
Pid:    29883                                                                   
PPid:   7168                                                                    
TracerPid:      0
Uid:    1000    1000    1000    1000
Gid:    1000    1000    1000    1000
FDSize: 256
Groups: 10 18 1000 1001 1005
VmPeak:    14144 kB
VmSize:    14144 kB
VmLck:         0 kB
VmHWM:       548 kB
VmRSS:       544 kB
VmData:     8388 kB
VmStk:        84 kB
VmExe:         4 kB
VmLib:      1528 kB
VmPTE:        32 kB
Threads:        2
SigQ:   1/40960
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000180000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: fffffffffffffeff
voluntary_ctxt_switches:        4447
nonvoluntary_ctxt_switches:     0

验毕!:)

你可能感兴趣的:(JOIN,多线程,gcc,cmd,null,终端)