strace Command in Linux: Trace System Calls and Signals
Learn strace command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
11 min read
Learn strace command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What strace Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
The strace command in linux is the ultimate diagnostic microscope for systems administrators, software engineers, and security analysts troubleshooting uncooperative binaries. When an application fails with an opaque error message, hangs indefinitely without logging, or crashes during initialization, strace reveals the exact sequence of kernel-level system calls—such as openat, read, write, connect, and mmap—that occurred leading up to the failure.
The strace command in Linux is a diagnostic and debugging utility that intercepts, monitors, and records the system calls made by a process and the signals received by it. By attaching to a running daemon via its Process ID (PID) or executing a command directly under tracing, strace exposes how user-space software interacts with the Linux kernel, making it invaluable for diagnosing missing files, permission denials, network timeouts, and performance bottlenecks.
Unlike source-level debuggers such as GDB that require debugging symbols (DWARF) and deep familiarity with application internals, strace operates entirely at the user-space and kernel boundary. It treats the target application as a black box, inspecting every request passed across the system call interface and capturing the input parameters, return values, and explicit kernel error codes (such as ENOENT, EACCES, or ETIMEDOUT).
Whether you are investigating why a compiled web server refuses to load an SSL certificate, identifying which configuration file is overriding defaults, or profiling slow database operations on a production host, strace provides the visibility required to isolate root causes in minutes.
What strace Does and When to Use It
Architecturally, strace relies on the Linux kernel ptrace(2) system call mechanism. When strace spawns a new binary or attaches to an existing running process using -p <PID>, it establishes a tracer-tracee relationship via PTRACE_ATTACH or PTRACE_SEIZE. The kernel then configures the target process to halt execution and deliver a SIGTRAP signal to the tracer every time a system call is entered (syscall-enter-stop) and every time the kernel completes the call and prepares to return to user space (syscall-exit-stop).
During each stop, strace queries the CPU registers (such as %rax, %rdi, %rsi, and %rdx on x86_64) using PTRACE_GETREGSET to decode the system call number, extract pointer arguments by reading the tracee memory space via process_vm_readv(2), and format the human-readable trace stream. Because this requires four context switches between tracer, kernel, and tracee for every individual system call, running strace imposes significant performance overhead—frequently slowing high-throughput programs by a factor of 10x to 50x while active.
Under the hood, strace gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -p <pid>, -f, -e <expr>, -o <file> turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The strace utility is packaged in strace across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether strace is installed and inspect which binary path and version your shell resolves:
type -a strace
strace --version 2>/dev/null || man -f strace
# Illustrative output (reviewed against documentation)
strace is /usr/bin/strace
strace (strace)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y strace
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y strace
# Arch Linux
sudo pacman -S --noconfirm strace
# Alpine Linux
sudo apk add --no-cache strace
Command Syntax, Arguments, and Exit Status Codes
strace [OPTIONS] [-e EXPR] [-p PID] [COMMAND [ARGS]]
The syntax for strace is flexible: strace [OPTIONS] COMMAND [ARGS] launches a new process under active tracing, while strace [OPTIONS] -p <PID> attaches dynamically to an already running background daemon or worker thread. By default, strace writes its diagnostic stream to standard error (stderr) to avoid corrupting standard application pipelines.
Crucial invocation arguments include -e trace=<set> to filter specific system call classes (such as file, network, process, or specific calls like openat,connect), -f to trace child processes spawned via fork(2), vfork(2), and clone(2), -o <filename> to route the trace output directly to a log file, and -c (or -C) to produce a summarized statistical histogram of call counts, error tallies, and execution time.
0— The traced command executed and exited with status 0, or strace completed statistical profiling cleanly.1— General strace operational failure, such as inability to allocate memory or write to the output log.126— The specified command was found but could not be invoked (e.g. lacked execute permissions).127— The command to be traced was not found in PATH or the binary does not exist.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-p <pid> | --attach=<pid> | Attaches strace directly to an existing running process identified by its PID. |
-f | --follow-forks | Follows and traces child processes created by fork, vfork, and clone calls. |
-e <expr> | --trace=<expr> | Filters system calls by class (e.g. -e trace=file,network) or specific names. |
-o <file> | --output=<file> | Redirects the strace diagnostic trace stream to a specified file path. |
-s <size> | --string-limit=<size> | Sets the maximum string length printed for buffers (default is 32 bytes). |
-c | --summary-only | Suppresses live tracing and prints a summary histogram of time, calls, and errors upon exit. |
-T | --syscall-times | Prints the time spent inside each individual system call at the end of the line. |
-tt | --absolute-timestamps | Prepends each trace line with absolute microsecond wall-clock time (HH:MM:SS.uuuuuu). |
-y | --decode-fds | Prints file paths and socket addresses associated with file descriptor integers. |
In production diagnostics, using bare strace without filtering flags is often overwhelming because modern glibc runtimes execute hundreds of memory management calls (brk, mmap, mprotect) before reaching main(). Using -e trace=file or -e trace=%net immediately eliminates noise by isolating filesystem operations or network sockets.
Combining -f (follow forks) with -o trace.log -ff is the gold standard for debugging multi-threaded and multi-process services (like Nginx, Apache, or PostgreSQL). The -ff modifier instructs strace to write separate log files for each thread and process (formatted as trace.log.<PID>), preventing race conditions and interleaved lines in the output.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Trace File Access and Missing Configuration Files
Trace only filesystem-related system calls to discover where an application searches for configuration files and which paths return ENOENT (No such file or directory).
strace -e trace=file nginx -t
# Illustrative output (reviewed against documentation)
openat(AT_FDCWD, "/etc/nginx/nginx.conf", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/nginx/conf.d/app.conf", O_RDONLY) = -1 ENOENT (No such file or directory)
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
+++ exited with 0 +++
The -e trace=file expression filters out memory allocations and signal handlers, showing exactly which files nginx opened and the missing app.conf error.
2. Attach strace to a Running Hanging Process by PID
Attach to a live worker process that is unresponsive or consuming CPU without producing log output to see what system call it is currently blocked on.
sudo strace -p 14205
# Illustrative output (reviewed against documentation)
strace: Process 14205 attached
futex(0x7f8a94002340, FUTEX_WAIT_PRIVATE, 2, NULL
strace hooks into PID 14205 via ptrace and reveals that the process is stuck in a thread lock waiting on a futex (fast userspace mutex).
3. Profile System Call Performance and Latency with a Summary Table
Run an administrative command or data pipeline under strace -c to identify which system calls consume the highest percentage of execution time.
strace -c tar -czf archive.tar.gz /var/log
# Illustrative output (reviewed against documentation)
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
54.21 0.142850 8 17850 read
32.14 0.084720 12 7060 write
8.12 0.021400 5 4280 120 openat
5.53 0.014580 3 4860 newfstatat
------ ----------- ----------- --------- --------- ----------------
100.00 0.263550 34050 120 total
The -c option aggregates execution data into a profiling table showing total elapsed time, invocation counts, and error occurrences per system call.
4. Decode File Descriptors and Trace Network Socket Connections
Trace outbound network connections while using -y to automatically translate numeric file descriptor integers into human-readable IP addresses and ports.
strace -e trace=network -y curl -s https://api.example.com > /dev/null
# Illustrative output (reviewed against documentation)
socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_TCP) = 3<TCP:[39281]>
connect(3<TCP:[39281]>, {sa_family=AF_INET, sin_port=htons(443), sin_addr=inet_addr("93.184.216.34")}, 16) = -1 EINPROGRESS (Operation now in progress)
poll([{fd=3<TCP:[93.184.216.34:443]>, events=POLLOUT}], 1, 30000) = 1 ([{fd=3, revents=POLLOUT}])
sendto(3<TCP:[93.184.216.34:443]>, "\26\3\1\2\0...", 517, MSG_NOSIGNAL, NULL, 0) = 517
The -y flag resolves socket descriptor 3 to TCP 93.184.216.34:443, making outbound TLS handshakes and connection states immediately decipherable.
5. Trace Multi-Threaded Processes and Expand String Truncation
Use -f to capture spawned child threads and -s 1024 to print long file paths, environment variables, or SQL queries without truncation.
strace -f -s 512 -e trace=write python3 app.py
# Illustrative output (reviewed against documentation)
[pid 22104] write(1, "[INFO] Connecting to postgresql://admin:[email protected]:5432/production_db\n", 74) = 74
[pid 22105] write(2, "[ERROR] Database connection failed: connection refused\n", 55) = 55
-f tracks individual thread executions ([pid 22104]), while -s 512 prevents strace from cutting off the connection string at the default 32 bytes.
6. Capture System Calls with High-Resolution Microsecond Timestamps
Prepend microsecond timestamps and system call durations to isolate exactly where a script stalls or encounters latency jitter.
strace -tt -T -e trace=nanosleep,poll python3 worker.py
# Illustrative output (reviewed against documentation)
14:22:01.104523 poll([{fd=4, events=POLLIN}], 1, 1000) = 0 (Timeout) <1.001085>
14:22:02.106214 nanosleep({tv_sec=0, tv_nsec=250000000}, NULL) = 0 <0.250142>
-tt prints absolute time (HH:MM:SS.uuuuuu) while -T appends call duration (<1.001085> seconds) to easily pinpoint timeout delays.
Real-World Workflows, Pipelines, and Shell Automation
Diagnosing Missing Shared Libraries or Permission Failures on Application Startup
When a custom binary or daemon crashes on startup without helpful log output, capture its initialization sequence to identify missing dependencies or permission errors.
#!/usr/bin/env bash
set -euo pipefail
TARGET_BIN="/opt/custom-app/bin/server"
LOG_FILE="/tmp/strace_startup_debug.log"
echo "Tracing startup execution of ${TARGET_BIN}..."
sudo strace -f -o "${LOG_FILE}" -e trace=file,process "${TARGET_BIN}" || true
echo "=== 1. Checking for missing shared libraries (.so) ==="
grep -E 'ENOENT.*\.so' "${LOG_FILE}" | head -n 5 || echo "No missing shared libraries detected."
echo "=== 2. Checking for permission denied errors (EACCES) ==="
grep -E 'EACCES' "${LOG_FILE}" || echo "No permission issues found."
echo "=== 3. Checking for failed configuration reads ==="
grep -E 'ENOENT.*\.(conf|yaml|json|env)' "${LOG_FILE}" | tail -n 5 || echo "No missing config files."
# Illustrative output (reviewed against documentation)
Tracing startup execution of /opt/custom-app/bin/server...
=== 1. Checking for missing shared libraries (.so) ===
openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/libssl.so.1.1", O_RDONLY) = -1 ENOENT (No such file or directory)
=== 2. Checking for permission denied errors (EACCES) ===
openat(AT_FDCWD, "/var/log/custom-app/error.log", O_WRONLY|O_CREAT|O_APPEND, 0644) = -1 EACCES (Permission denied)
=== 3. Checking for failed configuration reads ===
openat(AT_FDCWD, "/opt/custom-app/etc/server.yaml", O_RDONLY) = -1 ENOENT (No such file or directory)
Filtering the trace log for ENOENT and EACCES immediately pinpoints that the server failed due to missing libssl.so.1.1 and unprivileged write permissions to /var/log/custom-app.
Profiling Production Web Server Latency and System Call Bottlenecks
Attach to an active web server process for 10 seconds to generate a quantitative histogram of system call frequency, kernel time, and failure rates.
#!/usr/bin/env bash
set -euo pipefail
# Find the primary Nginx or PHP-FPM master PID
PID=$(pgrep -f 'nginx: worker process' | head -n 1)
if [ -z "${PID}" ]; then
echo "No matching worker process found."
exit 1
fi
echo "Attaching strace profiler to PID ${PID} for 10 seconds..."
sudo timeout 10 strace -c -p "${PID}" 2>&1 || true
# Illustrative output (reviewed against documentation)
strace: Process 8412 attached
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
48.12 0.096240 16 6015 epoll_wait
24.30 0.048600 6 8100 writev
14.18 0.028360 4 7090 read
8.20 0.016400 5 3280 recvfrom
5.20 0.010400 3 3466 120 accept4
------ ----------- ----------- --------- --------- ----------------
100.00 0.200000 27951 120 total
Using timeout 10 with strace -c provides a safe, bounded performance snapshot in production without leaving the tracer attached permanently.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding strace inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Exercising strace on production systems requires extreme caution. Attaching to high-traffic database or web worker processes introduces massive latency overhead (up to 50x slowdown) due to ptrace context switching. Furthermore, killing strace with SIGKILL (kill -9) instead of graceful SIGINT (Ctrl+C) can leave the target process paused in a TASK_STOPPED state indefinitely.
Tracing arbitrary processes is a strictly privileged operation controlled by Linux kernel security controls. On modern kernels, the Linux Security Module (Yama) restricts ptrace via /proc/sys/kernel/yama/ptrace_scope. When set to 1 (the default on Ubuntu and Debian), unprivileged users can only trace their own child processes spawned directly by the tracer; attaching to an already running daemon owned by the same user requires sudo or the CAP_SYS_PTRACE capability.
System call tracing can easily expose sensitive operational data. When an application reads configuration files, establishes database connections, or handles authentication credentials, arguments and buffers logged by strace (such as plaintext passwords in read, write, or execve calls) are written directly to stdout or the log file. Ensure strace output logs stored in /tmp or shared directories have restricted file permissions (e.g. chmod 600).
GNU/Linux, BSD, and BusyBox Implementation Differences
strace is specific to the Linux operating system because its implementation is tightly coupled to the Linux kernel ptrace(2) API and Linux system call numbering schemes. Other Unix and Unix-like operating systems provide their own native tracing utilities: FreeBSD and Solaris utilize truss, macOS and OpenBSD provide dtrace or dtruss, and NetBSD provides ktrace.
On minimal Linux container runtimes based on Alpine Linux or musl libc, strace is fully functional once installed via apk add strace. However, Docker and Kubernetes containers drop the CAP_SYS_PTRACE capability by default; running strace inside a container requires adding --cap-add=SYS_PTRACE --security-opt seccomp=unconfined to the container run configuration.
Troubleshooting Common Errors and Diagnostics
strace: attach: ptrace(PTRACE_SEIZE, ...): Operation not permitted
Root Cause: The kernel Yama ptrace_scope restriction is blocking attachment, or the caller lacks root/sudo privileges to trace processes owned by other users or daemons.
Resolution: Run strace with sudo, or temporarily adjust the kernel ptrace_scope setting to 0 (development environments only).
sudo strace -p <PID>
# Or temporarily relax Yama ptrace scope for local debugging:
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
Output contains truncated strings followed by '...' in arguments
Root Cause: By default, strace truncates printed string buffers at 32 bytes to conserve screen real estate and reduce performance impact.
Resolution: Pass the -s <size> option to specify a larger buffer limit (e.g. -s 1024 or -s 4096).
strace -s 2048 -e trace=write my_script.sh
Target process becomes unresponsive after strace session terminates
Root Cause: strace was terminated with SIGKILL (kill -9), preventing it from executing PTRACE_DETACH and leaving the target process trapped in TASK_STOPPED.
Resolution: Send SIGCONT to the target process ID to resume normal execution.
sudo kill -CONT <PID>
Alternatives, Related Commands, and Related Tutorials
- pstree Command in Linux: View the Process Tree Hierarchy — Practical syntax, flags, and examples for
pstree. - How to Kill a Process in Linux: kill, killall, and pkill Guide — Practical syntax, flags, and examples for
kill. - pidof Command in Linux: Find Process IDs by Program Name — Practical syntax, flags, and examples for
pidof. - ps Command in Linux: ps aux, ps -ef, Custom Columns, and Sorting — Practical syntax, flags, and examples for
ps. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides



Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!