prctl给线程命名和线程的一些操作
注意这里命名线程名称为
xx
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/prctl.h>
void* test(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, test, NULL);
pthread_join(tid, NULL);
return 0;
}
编译并运行:
gcc prctl.c -l pthread
./a.out
在另一个终端,通过ps找到a.out的pid:
[root@killinux ~]# ps -ef|grep a.ou
root 9764 8870 0 12:43 pts/2 00:00:00 ./a.out
root 9768 9747 0 12:43 pts/4 00:00:00 grep a.ou
[root@killinux ~]# cd /proc/9764
[root@killinux 9764]# cd task/
[root@killinux task]# ls
9764 9765
[root@killinux task]# pwd
/proc/9764/task
[root@killinux task]# cd 9765/
[root@killinux 9765]# ls
attr clear_refs cwd fd limits mem numa_maps oom_score_adj root sessionid stat syscall
auxv cmdline environ fdinfo loginuid mountinfo oom_adj pagemap sched smaps statm wchan
cgroup cpuset exe io maps mounts oom_score personality schedstat stack status
[root@killinux 9765]# cat cmdline
./a.out[root@killinux 9765]#
看命名是否奏效:
两个task的名字都是a.out
看线程名字用,线程的名字“xx”在这
[root@killinux 9764]#
ps -L -p 9764
PID LWP TTY TIME CMD
9764 9764 pts/2 00:00:00 a.out
9764 9765 pts/2 00:00:00
xx
[root@killinux 9764]#
-----------------------------------------------------------
stat文件和status文件中也有
[root@killinux 9764]# cat stat
9764 (a.out) S 8870 9764 8870 34818 9764 4202496 172 0 0 0 0 0 0 0 20 0 2 0 176577389 16850944 136 18446744073709551615 4194304 4196556 140734883346416 140734883346080 255523324077 0 0 0 0 18446744071579515721 0 0 17 3 0 0 0 0 0
[root@killinux 9764]# cd -
/proc/9764/task
[root@killinux task]# cd -
/proc/9764/task/9764
[root@killinux 9764]# cd ../9765/
[root@killinux 9765]#
cat stat
9765 (
xx) S 8870 9764 8870 34818 9764 4202560 17 0 0 0 0 0 0 0 20 0 2 0 176577389 16850944 136 18446744073709551615 4194304 4196556 140734883346416 140599854898320 255519799581 0 0 0 0 18446744071579464804 0 0 -1 0 0 0 0 0 0
[root@killinux 9765]#
cat status
Name:
xx
State: S (sleeping)
Tgid: 9764
Pid: 9765
PPid: 8870
TracerPid: 0
Uid: 0 0 0 0
Gid: 0 0 0 0
Utrace: 0
FDSize: 256
Groups: 0
VmPeak: 16456 kB
VmSize: 16456 kB
VmLck: 0 kB
VmHWM: 544 kB
VmRSS: 544 kB
VmData: 10440 kB
VmStk: 88 kB
VmExe: 4 kB
VmLib: 1792 kB
VmPTE: 44 kB
VmSwap: 0 kB
Threads: 2
SigQ: 1/62815
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000180000000
CapInh: 0000000000000000
CapPrm: ffffffffffffffff
参考
http://www.cnblogs.com/sunyubo/archive/2010/12/10/2282086.html
这个头文件不全