- Linux: detect at runtime that a process have multiple threads
- 5 Answers 5
- Show Threads Using PS Command in Linux
- Show Threads Using PS Command in Linux
- Show Threads with PID
- Show Threads with Application Name
- Show Threads with Filter
- Check threads in linux
- How to view threads of a process on Linux
- Order
- Topics
Linux: detect at runtime that a process have multiple threads
I’m asking about linux with recent glibc. Is there a way to detect that process consist of 1 thread or of several threads? Threads can be created by pthread, or bare clone(), so I need something rather universal. UPD: I want to detect threads of current process from it itself.
Duck, this code will be placed in .so library, which can be linked in various programs, both with pthread-based or clone-based threads.
I think if your library depends on knowing this, it won’t be robust. There might be only one thread just now, but another one starting very soon. How often do you plan to check?
5 Answers 5
Check if directory /proc/YOUR_PID/task/ contains only one subdirectory. If you have more than one thread in process there will be several subdirs.
The hardlink count can be used to count the subdirectories. This function returns the current number of threads:
#include int n_threads(void) < struct stat task_stat; if (stat("/proc/self/task", &task_stat)) return -1; return task_stat.st_nlink - 2; >
Hmm. Yes. There are threads for some processes. But to get information from /proc I need a lot of syscalls: opendir/readdir. Is there some easier way?
@caf, on my system the stat of proc/self/task returns 3 nr_links instead of 4 if I dont do a ls /proc/self/task or ps axm before stat.
I suppose you could run ‘ps’ (via popen() or similar) and parse its output, and see how many times your process’s ID (as returned by getpid()) appears in the output. There might be a better way, but that is what first comes to mind.
NO, please, no any subprocess starting :). It is so slow, and I need a fast way, like 1 syscall or some flag reading or so..
/proc is the standard way to do this in Linux. Tools like ‘ps’ work through /proc. In Linux 2.6, you can find the number of threads in /proc/self/stat, but that is not backwards compatible.
The answer from Victor is certainly the fastest, although you may want to consider using the ps library instead.
The name under Ubuntu is libprocps3-dev so you use install it using:
sudo apt-get install libprocps3-dev
The headers are found under /usr/include/proc .
Note that the library works by reading /proc. So it is the same as reading the files of interest directly, only it will know of differences between various versions and take care of that under the hood for you.
How much system calls will do procps to answer the question «process consist of 1 thread or of more than 1 thread»?
On the main answer, I see that many people ask about the compatibility problem. procps is definitely slow, but should work transparently on newer and older versions of Linux. It depends whether you need speed or long term compatibility.
A bit of an alternative way that hasn’t been mentioned, but is definitely the most hassle-free:
int ret = unshare(CLONE_THREAD); // CLONE_SIGHAND and/or CLONE_VM also works if (ret && errno == EINVAL) < // we are multi-threaded >
For single-threaded programs, this is a no-op. This won’t allow you to see the amount of created threads, but that wasn’t asked.
In addition, CLONE_THREAD, CLONE_SIGHAND, and CLONE_VM can be specified in flags if the caller is single threaded (i.e., it is not sharing its address space with another process or thread). In this case, these flags have no effect. [. ] If the process is multithreaded, then the use of these flags results in an error.
Edit: from your comments, it seems like this might be what you are looking for. It’s a single system call and doesn’t start any other processes.
Show Threads Using PS Command in Linux
In the modern operating systems, threads serve as a popular programming abstraction. These threads share resources like open files, space, and memory addresses when this happens. It avoids the inter-process communication (expensive IPC) channels and reduces forking overhead. As a result, threads perform a concurrent execution mechanism.
In Linux, threads are also known as LWP or Lightweight Processes. These threads created within the program have a “thread group ID”, the same as the program’s PID. There is an individual thread ID (TID) assigned to each thread. Scheduler threads in the Linux kernel share a few resources, which are standard processes.
Besides displaying the process-level information by default, classic command-line tools, such as top and ps, can display the thread-level information as well. Ps, top, and htop are classic commands that show you the process-level information by default. You can also view the thread-level information using the previous commands. This guide will only go through the ps command and explain how the ps command shows threads in Linux.
Show Threads Using PS Command in Linux
With the help of the ps command, you can view the threads with many filters like PID (Process ID), application name, etc. This command does not work on BSD or macOS, as there is no option to show that the thread and the -t parameter have a different meaning.
Let’s start with the following command in the terminal to list all the threads using the ps command:
Show Threads with PID
Here is the standard syntax of ps commands to view the threads using PIDs:
You can view the threads for specific PIDs. Follow the previous standard syntax and put the PID number which you want to know the threads.
For example, we use the PID . The syntax is as follows:
The “SPID” column shows the thread IDs in the previous output. And the “CMD” column represents the thread names.
Show Threads with Application Name
Here is the standard syntax of the ps command to view the threads using the application name:
Option | Description |
---|---|
-T | List all threads |
-C | Specifies the application name |
For example, let’s find out the thread related to the Bash application. Here is the basic command:
Show Threads with Filter
The standard syntax of the ps command is to view the threads using the filter as follows:
Option | Description |
---|---|
-T | List all threads |
-e | Shows all processes |
| | Pipes the output to the next command |
grep | It filters the content with the help of |
You can filter the content through the application name. Type and execute the following command to accomplish it:
You can also filter the threads using their PIDs:
In the previous output, you may notice that all the threads have the same PID. It means that all the previous threads are in the same process.
To find the sum of all the running threads in the system, you can execute the following command:
You can use the “pgrep” or “pidof” to get the process name’s process id:
Check threads in linux
- The number one in Linux and UNIX Health Checks
- Run hundreds of checks on your system in minutes
- Available for AIX and Red Hat Enterprise Linux
«It’s all about the ways clients can deploy Linux and UNIX systems to improve business performance.»
How to view threads of a process on Linux
Threads are a popular programming abstraction for parallel execution on modern operating systems. When threads are forked inside a program for multiple flows of execution, these threads share certain resources (e.g., memory address space, open files) among themselves to minimize forking overhead and avoid expensive IPC (inter-process communication) channel. These properties make threads an efficient mechanism for concurrent execution.
In Linux, threads (also called Lightweight Processes (LWP)) created within a program will have the same «thread group ID» as the program’s PID. Each thread will then have its own thread ID (TID). To the Linux kernel’s scheduler, threads are nothing more than standard processes which happen to share certain resources. Classic command-line tools such as ps or top, which display process-level information by default, can be instructed to display thread-level information.
Here are several ways to show threads for a process on Linux:
The «-T» option for the ps command enables thread views. The following command list all threads created by a process with
# ps -ef | grep 97947 deploy 97947 97942 1 00:51 ? 00:13:51 java
# ps -T -p 97947 PID SPID TTY TIME CMD 97947 97947 ? 00:00:00 java 97947 97948 ? 00:00:00 java 97947 97949 ? 00:00:00 java
The «SID» column represents thread IDs, and «CMD» column shows thread names.
Using the top command
The top command can show a real-time view of individual threads. To enable thread views in the top output, invoke top with «-H» option. This will list all Linux threads. You can also toggle on or off thread view mode while top is running, by pressing ‘H’ key.
top - 14:43:25 up 6 days, 5:40, 2 users, load average: 0.87, 0.33, 0.22 Threads: 684 total, 1 running, 683 sleeping, 0 stopped, 0 zombie %Cpu(s): 6.3 us, 4.0 sy, 0.0 ni, 89.6 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem : 7910136 total, 384812 free, 1603096 used, 5922228 buff/cache KiB Swap: 8388604 total, 8239100 free, 149504 used. 5514264 avail Mem
Note how in the example above the number of threads on the system is listed.
To restrict the top output to a particular process and check all threads running inside the process:
A more user-friendly way to view threads per process is via htop, an ncurses-based interactive process viewer. This program allows you to monitor individual threads in tree views.
To enable thread views in htop, launch htop, and press F2 to enter htop setup menu. Choose «Display option» under «Setup» column, and toggle on «Tree view» and «Show custom thread names» options. Presss F10 to exit the setup.
UNIX Health Check delivers software to scan Linux and AIX systems for potential issues. Run our software on your system, and receive a report in just a few minutes. UNIX Health Check is an automated check list. It will report on perfomance, capacity, stability and security issues. It will alert on configurations that can be improved per best practices, or items that should be improved per audit guidelines. A report will be generated in the format you wish, and the report includes the issues discovered and information on how to solve the issues as well.
Interested in learning more?
- Try a demo version
- Order UNIX Health Check
- Contact us
Order
No time to lose? Need to know what’s wrong with
your UNIX system now? Then get started TODAY!
Topics
- AIX (231)
- Backup & restore (42)
- DB2 (6)
- Docker (1)
- EMC (13)
- EMC Networker (3)
- Fun (3)
- GPFS (10)
- Hardware (12)
- HMC (15)
- HP Output Server (17)
- IBM Content Manager (20)
- Installation (30)
- Kubernetes (1)
- Logical Partitioning (6)
- LVM (16)
- Monitoring (15)
- Networking (32)
- NIM (12)
- ODM (4)
- Oracle (3)
- Performance (13)
- PowerHA / HACMP (31)
- Red Hat / Linux (103)
- SAN (20)
- Scripting (3)
- SDD (7)
- Security (45)
- Spectrum Protect (18)
- SSA (3)
- Storage (51)
- Sun Solaris (3)
- System Admin (249)
- Veritas NetBackup (1)
- Virtual I/O Server (5)
- Virtualization (11)
- VMWare (1)
- WebSphere (6)
- X11 (1)
This website is owned and operated by UNIX Health Check and protected by copyright. The material and information on this website may not be sold, duplicated on other websites or in any other forms, incorporated in commercial documents or products, or used for promotional purposes, without the prior written approval of UNIX Health Check.