#define _GNU_SOURCE /* See feature_test_macros(7) */ #include <pthread.h> int pthread_setname_np(pthread_t thread, const char *name); int pthread_getname_np(pthread_t thread, char *name, size_t len);
Compile and link with -pthread.
The pthread_getname_np() function can be used to retrieve the name of the thread. The thread argument specifies the thread whose name is to be retrieved. The buffer name is used to return the thread name; len specifies the number of bytes available in name. The buffer specified by name should be at least 16 characters in length. The returned thread name in the output buffer will be null terminated.
The pthread_getname_np() function can fail with the following error:
If either of these functions fails to open /proc/self/task/[tid]/comm, then the call may fail with one of the errors described in open(2).
Interface | Attribute | Value |
pthread_setname_np(), pthread_getname_np() | Thread safety | MT-Safe |
The following shell session shows a sample run of the program:
$ ./a.out
Created a thread. Default name is: a.out
The thread name after setting it is THREADFOO.
haZ # Suspend the program
[1]+ Stopped ./a.out
$ ps H -C a.out -o 'pid tid cmd comm'
PID TID CMD COMMAND
5990 5990 ./a.out a.out
5990 5991 ./a.out THREADFOO
$ cat /proc/5990/task/5990/comm
a.out
$ cat /proc/5990/task/5991/comm
THREADFOO
#define NAMELEN 16
#define errExitEN(en, msg) \
do { errno = en; perror(msg); \
exit(EXIT_FAILURE); } while (0)
static void *
threadfunc(void *parm)
{
sleep(5); // allow main program to set the thread name
return NULL;
}
int
main(int argc, char **argv)
{
pthread_t thread;
int rc;
char thread_name[NAMELEN];
rc = pthread_create(&thread, NULL, threadfunc, NULL);
if (rc != 0)
errExitEN(rc, "pthread_create");
rc = pthread_getname_np(thread, thread_name, NAMELEN);
if (rc != 0)
errExitEN(rc, "pthread_getname_np");
printf("Created a thread. Default name is: %s\n", thread_name);
rc = pthread_setname_np(thread, (argc > 1) ? argv[1] : "THREADFOO");
if (rc != 0)
errExitEN(rc, "pthread_setname_np");
sleep(2);
rc = pthread_getname_np(thread, thread_name,
(argc > 2) ? atoi(argv[1]) : NAMELEN);
if (rc != 0)
errExitEN(rc, "pthread_getname_np");
printf("The thread name after setting it is %s.\n", thread_name);
rc = pthread_join(thread, NULL);
if (rc != 0)
errExitEN(rc, "pthread_join");
printf("Done\n");
exit(EXIT_SUCCESS);
}