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 s开发者_JAVA百科omething rather universal.
UPD: I want to detect threads of current process from it itself.
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 <sys/stat.h>
int n_threads(void)
{
struct stat task_stat;
if (stat("/proc/self/task", &task_stat))
return -1;
return task_stat.st_nlink - 2;
}
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.
/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.
See http://procps.sourceforge.net/index.html for details.
精彩评论