How to Display Threads Associated with a Process in Linux
Nezar Fadle
Digital Signage Engineer | Specialist in Creating Dynamic and Engaging Displays
In this post, we will explore how to display the threads associated with a process in Linux. To do this, we will create a simple C program that creates a thread called "MyThread".
To start, let's create a file called "thread.c" and add the following code:
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
void * childThread() {
? ? printf( "Child Thread: Start sleeping \n" );
? ? getchar();
}
int main() {
? ? pthread_t myThread;
? ? pthread_create( &myThread, NULL, childThread, NULL );
? ? pthread_setname_np( myThread, "myThread" );
? ? printf( "Main Thread: Start sleeping \n\n" );
? ? printf( "Press enter twice to exit \n" );
? ? getchar();
? ? printf( "Bye bye!\n" );
? ? return 0;
}
Now, let's compile and run the program with the following command:
cc -pthread thread.c -o thread && ./thread
To display the threads associated with this process, we first need to find the process ID of our program. To do this, run the following command:
ps -C thread
This should output something similar to:
领英推荐
PID TTY TIME CM
8970 pts/4 00:00:00 thread
In this case, the process ID of our program is 8970. To display the threads associated with this process, we can use the "top" command with the "-H" and "-p" flags. Run the following command:
top -H -p 8970
This should output something similar to:
top - 00:51:13 up 2:56, 7 users, load average: 0.32, 0.48, 0.
Threads: 2 total, 0 running, 2 sleeping, 0 stopped, 0 zombie
%Cpu(s): 9.5 us, 1.2 sy, 0.0 ni, 88.6 id, 0.3 wa, 0.3 hi, 0.0 si, 0.0 st
KiB Mem: 3557480 total, 3168228 used, 389252 free, 137776 buffers
KiB Swap: 1000444 total, 0 used, 1000444 free, 1437184 cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8970 root 20 0 10520 304 244 S 0.0 0.0 0:00.00 thread
8971 root 20 0 10520 304 244 S 0.0 0.0 0:00.00 myThread
This will display all of the threads associated with the process with ID 8970, including the main thread and the "myThread" thread that we created. Alternatively, you can press "V" to switch to the forest mode in top, which will display the threads in a tree structure.
By following these steps, you should now be able to display the threads associated with a running process in Linux.