xref: /aosp_15_r20/external/musl/src/thread/pthread_setname_np.c (revision c9945492fdd68bbe62686c5b452b4dc1be3f8453)
1 #define _GNU_SOURCE
2 #include <fcntl.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <sys/prctl.h>
6 
7 #include "pthread_impl.h"
8 
pthread_setname_np(pthread_t thread,const char * name)9 int pthread_setname_np(pthread_t thread, const char *name)
10 {
11 	int fd, cs, status = 0;
12 	char f[sizeof "/proc/self/task//comm" + 3*sizeof(int)];
13 	size_t len;
14 
15 	if ((len = strnlen(name, 16)) > 15) return ERANGE;
16 
17 	if (thread == pthread_self())
18 		return prctl(PR_SET_NAME, (unsigned long)name, 0UL, 0UL, 0UL) ? errno : 0;
19 
20 	snprintf(f, sizeof f, "/proc/self/task/%d/comm", thread->tid);
21 	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
22 	if ((fd = open(f, O_WRONLY|O_CLOEXEC)) < 0 || write(fd, name, len) < 0) status = errno;
23 	if (fd >= 0) close(fd);
24 	pthread_setcancelstate(cs, 0);
25 	return status;
26 }
27