Overview
strace traces all system calls and signal events made by a specified command or attached to a running process in real-time. This is essential for understanding the low-level behavior of programs, including file I/O, network communication, and memory management.
Key Features
- Trace system calls and signals of a process
- Display arguments, return values, and error codes for each call
- Attach to a running process for tracing
- Trace child processes as well
- Filter specific system calls or signals
Key Options
strace offers various options to finely control the tracing method and output format.
Basic Tracing Options
Output Control
Filtering
Generated command:
Try combining the commands.
Description:
`strace` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Various usage examples of strace.
Basic Command Tracing
strace ls
Traces the system calls of the `ls` command.
Saving Trace Results to a File
strace -o date_trace.log date
Saves the system calls of the `date` command to the file `date_trace.log`.
Tracing a Running Process
strace -p 12345
Attaches to a process with PID 12345 and traces its system calls. (Replace 12345 with the actual process ID.)
Tracing Child Processes
strace -f bash -c "echo Hello, strace!"
Traces the system calls of both `bash` and `echo` when executing `echo` in a `bash` shell.
Filtering Specific System Calls
strace -e trace=open,read,write cat /etc/hosts
Traces if the `cat /etc/hosts` command uses `open`, `read`, and `write` system calls.
Checking System Call Execution Time
strace -T ls
Prints the time spent on each system call.
Installation
strace may not be included by default in most Linux distributions. You can install it using the following commands.
Debian/Ubuntu
sudo apt update && sudo apt install strace
Install using the APT package manager.
CentOS/RHEL 7
sudo yum install strace
Install using the YUM package manager.
Fedora/RHEL 8+
sudo dnf install strace
Install using the DNF package manager.
Tips & Precautions
strace is powerful, but there are a few things to consider when using it.
Performance Impact
strace intercepts system calls, which can significantly impact the performance of the program being traced, especially for I/O-intensive applications. Use with caution in production environments.
Interpreting Output
strace output can be very verbose. It's recommended to filter the information you need (-e) or save it to a file (-o) for analysis. For detailed information on specific system calls, use `man 2 <syscall_name>`.
Permissions
Root privileges are required to trace other users' processes or system-wide behavior.
Difference from Debugging Tools
strace operates at the system call level. Unlike debuggers like `gdb`, it cannot directly manipulate program variables or function calls, nor can it display stack traces. The two tools can be used complementarily.