xref: /aosp_15_r20/external/musl/src/thread/pthread_getname_np.c (revision c9945492fdd68bbe62686c5b452b4dc1be3f8453)
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)) == -1) status = errno;
21 	else name[len-1] = 0; /* remove trailing new line only if successful */
22 	if (fd >= 0) close(fd);
23 	pthread_setcancelstate(cs, 0);
24 	return status;
25 }
26