Is there a way to know, at a real time, what threads are opened and what application opened them?
I guess ps -L
should do the trick.
Here is ps
documentation.
Not sure if you ask how to do that programmaticaly, but in this case, since ps
is open-source, so you can probably take a look at the sources.
You can look in /proc/<PID>/task/
(where <PID>
is a process-ID) which will have a number of subdirectories, each with the name equal to the thread-ID of one of the threads in that task.
Note that this is only sort-of real-time though -- unless you were to "freeze" the entire system for the duration, the information you get can always be stale, because a process may create or destroy threads even as you're looking at the data.
In modern Linuxes, threads are very much like processes. Each thread has an LWP ("light-weight process") identifier, which is internally implemented as PID. However, if such "light-weight process" (i.e. thread) is queried for a PID, the system yields the PID of the process that spawned the thread (instead of LWP). Note also, that if the process has only one thread, it's LWP will be equal to its PID.
ps
is capable to processing threads with -L
modifier, as ereOn described in his answer. But I should note that ps
is not just for manual invocation. It has capabilities to print output in such a way that's easy to parse by another program.
The following command will print LWPs (-o lwp=
) and PIDs (-o pid=
) of all (-A
) threads (-L
) in the system. Each string represents one thread, second column being the process that spawned it:
$ ps -A -L -o lwp= -o pid=
...
27747 27747
27749 27749
27750 27750
27751 27750
27752 27750
27755 27750
27756 27750
27772 27772
27858 27858
30457 30457
30886 30886
Quite easy to parse with C or C++, isn't it? To actually read this from your program, you can use popen
or one of its C++ equivalents.
Note that using ps
is not only easier than reading /proc
. It's also much safer than manually parsing /proc
filesystem. ps
is a POSIX command*, it's guaranteed to work; it does use /proc
under Linux, but that's internal details. When underlying infrastructure changes, ps
will be rewritten, and will keep working, while your code, if written based on /proc
, will break.
*To be honest, POSIX does not specify -L
switch. But in any Linux, which has GNU toolchain, it will be available.