我是靠谱客的博主 悦耳水池,这篇文章主要介绍Linux C/C++编程:prctl与pthread_setname_npprctlpthread_setname_np,现在分享给大家,希望可以做个参考。
prctl
理论
复制代码
1
2
3
4// 用 prctl 给线程命名, prctl是个系统调用 #include <sys/prctl.h> int prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5);
实践
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#include <zconf.h> #include <sys/prctl.h> #include <stdio.h> #include <pthread.h> 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; }
执行:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23$ gcc main.c -l pthread $ ps aux | grep a.out oceanst+ 9725 0.0 0.0 14704 384 pts/1 Sl+ 18:52 0:00 ./a.out $ ps -L -p 9725 PID LWP TTY TIME CMD 9725 9725 pts/1 00:00:00 a.out 9725 9726 pts/1 00:00:00 xx
pthread_setname_np
prctl()只能设置/获取当前线程的名字
在glibc 2.12之后的版本中提供了两个扩展的接口pthread_setname_np()和pthread_getname_np(),可以在进程中设置和读取其他线程的名字。
检查glibc版本:
复制代码
1
2
3# getconf GNU_LIBC_VERSION glibc 2.17
可以使用feature_test_macro_GNU_SOURCE来检查此功能是否可用:
复制代码
1
2
3
4#ifdef _GNU_SOURCE pthread_setname_np(tid, "someName"); #endif
理论
复制代码
1
2
3
4
5
6
7
8
9#include <pthread.h> /* * 功能值:该pthread_setname_np()函数设置目标线程的名称。由名称指定的缓冲区必须包含一个长度为15个字符或更少的空终止字符串(不包括NULL)。如果名称长度超过15个字符,则多余的字符将被忽略。如果name为null,则该线程变为未命名 * 返回值:成功返回0 */ int pthread_setname_np(pthread_t thread, const char *name); //获取线程名称 int pthread_getname_np(pthread_t thread, char *name);
实践
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47#define _MULTI_THREADED #include <pthread.h> #include <stdio.h> #include <string.h> #include <unistd.h> void *threadfunc(void *parm) { printf("In the thread.n"); sleep(45); // allow main program to set the thread name return NULL; } int main(int argc, char **argv) { pthread_t thread; int rc=0; char theName[16]; memset(theName, 0x00, sizeof(theName)); printf("Create thread using the default attributesn"); rc = pthread_create(&thread, NULL, threadfunc, NULL); if(0 == rc) { #ifdef _GNU_SOURCE rc = pthread_setname_np(thread, "THREADNAMEISTOOLONG"); sleep(10); if(0 == rc) { rc = pthread_getname_np(thread, theName); if(0 == rc) { printf("The thread name is %s.n", theName); } } #endif rc = pthread_join(thread, NULL); } if(0 != rc) { printf("An error occurred - %dn", rc); } printf("Main completedn"); return(rc); }
用prctl给线程命名
最后
以上就是悦耳水池最近收集整理的关于Linux C/C++编程:prctl与pthread_setname_npprctlpthread_setname_np的全部内容,更多相关Linux内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复