ps display thread name

荒凉一梦 提交于 2020-06-24 08:49:10

问题


Is there a way for ps (or similar tool) to display the pthread's name? I wrote the following simple program:

// th_name.c
#include <stdio.h>
#include <pthread.h>

void * f1() {
    printf("f1 : Starting sleep\n");
    sleep(30);
    printf("f1 : Done sleep\n");
}

int main() {

    pthread_t  f1_thread;
    pthread_create(&f1_thread, NULL, f1, NULL);
    pthread_setname_np(f1_thread, "f1_thread");

    printf("Main : Starting sleep\n");
    sleep(40);
    printf("Main : Done sleep\n");
    return 0;

}

Is there a command/utility (like ps) that I can use to display the threads for the above program, along with their name.

$ /tmp/th_name > /dev/null &
[3] 2055
$ ps -eLf | egrep "th_name|UID"
UID        PID  PPID   LWP  C NLWP STIME TTY          TIME CMD
aal      31088 29342 31088  0    2 10:01 pts/4    00:00:00 /tmp/th_name
aal      31088 29342 31089  0    2 10:01 pts/4    00:00:00 /tmp/th_name
aal      31095 29342 31095  0    1 10:01 pts/4    00:00:00 egrep th_name|UID

I am running my program on Ubuntu 12.10.


回答1:


note the man page of pthread_setname_np(),which have showed how to get the threads' names:

pthread_setname_np() internally writes to the thread specific comm file under /proc filesystem: /proc/self/task/[tid]/comm. pthread_getname_np() retrieves it from the same location.

and

Example

The program below demonstrates the use of pthread_setname_np() and pthread_getname_np().

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.

^Z #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




回答2:


With procps-ng (https://gitlab.com/procps-ng/procps) there are output option -L and -T which will print threads names:

$ ps -eL
$ ps -eT

-l long format may be used with them:

$ ps -eLl
$ ps -eTl

but -f option will replace thread name with full command line which is the same for all threads.




回答3:


Show the thread IDs and names of the process with PID 12345:

ps H -o 'tid comm' 12345


来源:https://stackoverflow.com/questions/17514771/ps-display-thread-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!