merlin2011
merlin2011

Reputation: 75579

How do I tell how many threads a Linux binary is creating without source?

Suppose I have a generic binary without source and I want to determine whether it is running serially or spawns multiple threads.

Is there a way I can do this from the linux command line?

Upvotes: 5

Views: 3410

Answers (3)

Ortwin Angermeier
Ortwin Angermeier

Reputation: 6203

Just run: cat /proc/<pid>/stat | awk '{print $20}' to get the number of threads of a running process.

proc manpage

Upvotes: 1

nemo
nemo

Reputation: 57729

You can use ps for that. From man ps:

-L     Show threads, possibly with LWP and NLWP columns.

So you can do:

$ ps -L <pid>

and it will show you something like this:

 PID   LWP TTY      STAT   TIME COMMAND
4112  4112 ?        Sl    65:35 /usr/lib/firefox/firefox
4112  4116 ?        Sl     0:04 /usr/lib/firefox/firefox

Each line of the output corresponds to one thread. This of course, only works for a certain moment in time. To track the spawning of threads, use strace, as suggested by Jonathon Reinhart.

An alternative to strace is, of course, gdb. See this question for details on managing threads in gdb. You may also read the thread section of the gdb manual. Quick introduction:

$ gdb /usr/lib/firefox/firefox <pid>
[... initialization output ...]
> info threads    # lists threads
> thread <nr>     # switch to thread <nr>

Your comment:

How can I figure out where to set an instruction-level breakpoint if the program only takes seconds to run?

This answer might help you here, as it shows how to break on thread creation (with pthread_create) using gdb. So every time a thread is created, execution stops and you might investigate.

Upvotes: 4

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137497

First install strace.

$ yum install strace

Run the program with strace, and look for clone or fork system calls. Here's a quick example with a program I wrote that just calls fork and returns.

$ strace ./a.out 

execve("./a.out", ["./a.out"], [/* 43 vars */]) = 0
brk(0)                                  = 0x74f000
...
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fb22b16da10) = 6567
exit_group(1)                           = ?
+++ exited with 1 +++

Upvotes: 4

Related Questions