backtrace - Linux
Overview
The backtrace
command generates a stack trace of a running program or process, showing the function calls that led to the current context. This information can be invaluable for debugging errors or understanding code execution flow.
Syntax
backtrace [OPTIONS] [pid]
Options/Flags
- -a, –all: Print all frames, including those in shared libraries.
- -c, –count N: Print only the last
N
frames. - -f, –file: Print the file and line number for each frame.
- -i, –ignored N: Ignore the first
N
frames (main and wrapper functions). - -o, –output FILE: Write output to specified file.
- -s, –symbols: Resolve symbols to demangled function names.
- -t, –threads: Print stack traces for all threads in the process.
- -v, –verbose: Print additional information, such as arguments and local variables.
Examples
- Print the last 10 stack frames for the current process:
backtrace -c 10
- Print the full stack trace for process with PID 1234:
backtrace 1234
- Resolve symbols in the stack trace of all threads:
backtrace -st
- Write the stack trace to a file:
backtrace -o stack.txt
Common Issues
- Missing symbols: If symbols are not resolved (
-s
flag), you may get addresses instead of function names. Ensure that the necessary debug symbols are available. - Truncated stack trace: The stack trace may be truncated if the process has exceeded
ulimit -c
. Increase the limit to allow for more frames.
Integration
- Use
backtrace
with tools likegdb
for in-depth debugging. - Integrate
backtrace
into scripts or pipelines to automate error reporting.
Related Commands
- gdb: A powerful debugger that can display stack traces and inspect memory.
- strace: A tool that traces system calls and can provide context for stack frames.