1 From 8fb28b0b3e7a5e958fb844722a4b2ef9bc244af1 Mon Sep 17 00:00:00 2001
2 From: Felix Janda <felix.janda@posteo.de>
3 Date: Fri, 16 Sep 2016 20:54:00 -0400
4 Subject: add pthread_setname_np
6 the thread name is displayed by gdb's "info threads".
8 include/pthread.h | 1 +
9 src/thread/pthread_setname_np.c | 26 ++++++++++++++++++++++++++
10 2 files changed, 27 insertions(+)
11 create mode 100644 src/thread/pthread_setname_np.c
13 diff --git a/include/pthread.h b/include/pthread.h
14 index 3d2e0c4..94ef919 100644
15 --- a/include/pthread.h
16 +++ b/include/pthread.h
17 @@ -214,6 +214,7 @@ struct cpu_set_t;
18 int pthread_getaffinity_np(pthread_t, size_t, struct cpu_set_t *);
19 int pthread_setaffinity_np(pthread_t, size_t, const struct cpu_set_t *);
20 int pthread_getattr_np(pthread_t, pthread_attr_t *);
21 +int pthread_setname_np(pthread_t, const char *);
22 int pthread_tryjoin_np(pthread_t, void **);
23 int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);
25 diff --git a/src/thread/pthread_setname_np.c b/src/thread/pthread_setname_np.c
27 index 0000000..82d35e1
29 +++ b/src/thread/pthread_setname_np.c
35 +#include <sys/prctl.h>
37 +#include "pthread_impl.h"
39 +int pthread_setname_np(pthread_t thread, const char *name)
41 + int fd, cs, status = 0;
42 + char f[sizeof "/proc/self/task//comm" + 3*sizeof(int)];
45 + if ((len = strnlen(name, 16)) > 15) return ERANGE;
47 + if (thread == pthread_self())
48 + return prctl(PR_SET_NAME, (unsigned long)name, 0UL, 0UL, 0UL) ? errno : 0;
50 + snprintf(f, sizeof f, "/proc/self/task/%d/comm", thread->tid);
51 + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
52 + if ((fd = open(f, O_WRONLY)) < 0 || write(fd, name, len) < 0) status = errno;
53 + if (fd >= 0) close(fd);
54 + pthread_setcancelstate(cs, 0);