1 #define _GNU_SOURCE
2 #include <pthread.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <stdlib.h>
8
9 #define NAMELEN 16
10
11 #define errExitEN(en, msg) \
12 do { errno = en; perror(msg); exit(EXIT_FAILURE); \
13 } while (0)
14
threadfunc(void * parm)15 static void *threadfunc(void *parm)
16 {
17 sleep(1); // allow main program to set the thread name
18 return NULL;
19 }
20
main(int argc,char ** argv)21 int main(int argc, char **argv)
22 {
23 pthread_t thread;
24 int rc;
25 char thread_name[NAMELEN];
26 char set_thread_name[] = "THREADFOO";
27 char default_name[] = "pthread_getname";
28
29 rc = pthread_getname_np(pthread_self(), thread_name, NAMELEN-1);
30 if (rc != ERANGE) errExitEN(rc, "pthread_getname_np(invalid args[len]) failed");
31
32 rc = pthread_getname_np(pthread_self(), thread_name, NAMELEN);
33 if (rc != 0) errExitEN(rc, "pthread_getname_np failed");
34 if(strcmp(thread_name, default_name) != 0) perror("pthread name comparison failed");
35
36 rc = pthread_create(&thread, NULL, threadfunc, NULL);
37 if (rc != 0) errExitEN(rc, "pthread_create failed");
38
39 rc = pthread_setname_np(thread, (argc > 1) ? argv[1] : set_thread_name);
40 if (rc != 0) errExitEN(rc, "pthread_setname_np failed");
41
42 rc = pthread_getname_np(thread, thread_name, (argc > 2) ? atoi(argv[1]) : NAMELEN);
43 if (rc != 0) errExitEN(rc, "pthread_getname_np failed");
44 if(strcmp(thread_name, set_thread_name) != 0) perror("pthread name comparison failed");
45
46 rc = pthread_join(thread, NULL);
47 if (rc != 0) errExitEN(rc, "pthread_join failed");
48
49 exit(EXIT_SUCCESS);
50 }