1 #define _GNU_SOURCE
2 #include <fcntl.h>
3 #include <unistd.h>
4 #include <sys/prctl.h>
5
6 #include "pthread_impl.h"
7
pthread_getname_np(pthread_t thread,char * name,size_t len)8 int pthread_getname_np(pthread_t thread, char *name, size_t len)
9 {
10 int fd, cs, status = 0;
11 char f[sizeof "/proc/self/task//comm" + 3*sizeof(int)];
12
13 if (len < 16) return ERANGE;
14
15 if (thread == pthread_self())
16 return prctl(PR_GET_NAME, (unsigned long)name, 0UL, 0UL, 0UL) ? errno : 0;
17
18 snprintf(f, sizeof f, "/proc/self/task/%d/comm", thread->tid);
19 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
20 if ((fd = open(f, O_RDONLY|O_CLOEXEC)) < 0 || (len = read(fd, name, len)) < 0) status = errno;
21 else name[len-1] = 0;
22 /* remove trailing new line only if successful*/
23 /*It seems that Linux indeed always adds a newline, so removing it
24 unconditionally seems fine.*/
25
26 if (fd >= 0) close(fd);
27 pthread_setcancelstate(cs, 0);
28 return status;
29 }