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
9int 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)) < 0 || write(fd, name, len) < 0) status = errno;
23	if (fd >= 0) close(fd);
24	pthread_setcancelstate(cs, 0);
25	return status;
26}
27