5

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?

6
  • 3
    You can use top or htop to find it or even use gdb and arbitrarily halt the program and check the threads it has spawned. Commented May 16, 2013 at 20:45
  • 2
    Monitor the program with strace and look for the fork or clone system calls. Commented May 16, 2013 at 20:46
  • How can I figure out where to set an instruction-level breakpoint if the program only takes seconds to run? Commented May 16, 2013 at 20:47
  • Also %50 of Linux binaries can be decompiled so as to extract most of the source code. I believe Netbeans has an import from binary command. Commented May 16, 2013 at 20:50
  • @JonathonReinhart: fork() is not involved in thread creation. Commented May 17, 2013 at 12:49

3 Answers 3

4

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 +++ 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that how I'd do it. To print the number of threads on stdout: strace ./a.out 2>&1 | grep -c clone.
4

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.

Comments

1

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

proc manpage

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.