On 04/12/2013 10:51 AM, Noob wrote:
> AFAICT, there are (at least) two ways to give a name to a thread
> in a multi-threaded Linux program:
[ A bit off-topic on cup as it is Linux-specific ]
A strange behavior to be noticed: on Linux, if you change the "main"
thread's name (ie. the thread who ran main()) using any of these
methods, the top's "COMMAND" will be also replaced by the corresponding
name, and the "killall" Linux shell script command won't be able to find
the original program (but will be able to find the new title)
You may consider doing that:
if (!pthread_equal(pthread_self(), main_thread) != 0) {
return pthread_setname_np(pthread_self(), name);
} else {
...
> What is the preferred way in Linux?
Most probably the high-level one (pthread_setname_np()) which might be
standardized one day
> perhaps it even uses prctl itself?
Yes.
(glibc 2.17 nptl/sysdeps/unix/sysv/linux/pthread_setname.c extract)
int
pthread_setname_np (th, name)
pthread_t th;
const char *name;
{
const struct pthread *pd = (const struct pthread *) th;
/* Unfortunately the kernel headers do not export the TASK_COMM_LEN
macro. So we have to define it here. */
#define TASK_COMM_LEN 16
size_t name_len = strlen (name);
if (name_len >= TASK_COMM_LEN)
return ERANGE;
if (pd == THREAD_SELF)
return prctl (PR_SET_NAME, name) ? errno : 0;
..
}