MetallicPriest
MetallicPriest

Reputation: 30825

How to dump thread stacks

I want to dump the stacks of the threads in a file. How can I do that in linux? How can I find the starting address of the stack and its size? Note that I want to do this progammatically from the same process (not using ptrace, gdb or something like that).

Upvotes: 3

Views: 5215

Answers (5)

Why do you want to dump your threads' stacks??

Do you want to get some application checkpointing ? If you want it, there are some libraries implementing it, even imperfectly, but usefully in practice.

The point is, that even if you manage to dump your threads' stacks in a file, I'm not sure you'll be able to do somehing useful with that file. You won't even be able to restart your application using these stacks, because when restarted (even in the same configuration) the stacks might be located elsewhere (because of ASLR), unless you write a 0 digit into /proc/sys/kernel/randomize_va_space

I heard there is also some linux libraries which force a running process to dump a core file (that you could examine with gdb later) without aborting that process.

A call stack is something very brittle, and you cannot re-use it without precautions.

If you just want to inspect your call stack, look into Ian Taylor's libbacktrace.

Notice that several checkpointing infrastructures (including SBCL's save-lisp-and-die) are not capable of restoring any other threads than the main one. That says something about the difficulty of managing pthread-s stacks.

Upvotes: 1

MK.
MK.

Reputation: 34597

Glibc has function called backtrace which does what you want.

http://www.delorie.com/gnu/docs/glibc/libc_665.html

http://www.linuxjournal.com/article/6391?page=0,0

Last time I tried it, results were less than perfect, but somewhat useful. YMMV.

Upvotes: 1

Brett Hale
Brett Hale

Reputation: 22378

Use the pthread_attr_getstack function; this yields the thread's stack address and size.

Upvotes: 2

Chris
Chris

Reputation: 935

if you use the gnu c lib, you can use the backtrace() function

http://www.gnu.org/s/hello/manual/libc/Backtraces.html

Upvotes: 2

robinst
robinst

Reputation: 31457

Use gdb to attach to a running process via its PID (process ID):

gdb -p 1234

And then type bt to get a backtrace.

Upvotes: 1

Related Questions