Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
strace Command in Linux: Trace System Calls and Signals
AI Executive SummaryWebsiteVidya AI

11 min read

Learn strace command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What strace Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
strace Command in Linux: Trace System Calls and Signals — syntax, flags, and practical terminal workflow diagram
strace Command in Linux: Trace System Calls and Signals — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-p <pid>--attach=<pid>Attaches strace directly to an existing running process identified by its PID.
-f--follow-forksFollows 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-onlySuppresses live tracing and prints a summary histogram of time, calls, and errors upon exit.
-T--syscall-timesPrints the time spent inside each individual system call at the end of the line.
-tt--absolute-timestampsPrepends each trace line with absolute microsecond wall-clock time (HH:MM:SS.uuuuuu).
-y--decode-fdsPrints 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.

Advertisement

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

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>

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Yes. Run strace with the command or attach to the hanging process using sudo strace -p <PID>. The very last system call displayed on the screen is the exact operation (such as futex, read on a network socket, or flock) where the process is currently blocked.
Use the -z or -Z flags in modern strace versions: strace -Z COMMAND prints only system calls that failed (returned a negative error code), filtering out all successful operations.
Use strace in production only with strict filtering (such as strace -e trace=openat) or bounded profiling (timeout 5 strace -c -p <PID>). Unfiltered tracing introduces severe ptrace context-switch latency that can degrade request throughput.
strace intercepts kernel system calls (interactions between the program and the Linux kernel), whereas ltrace intercepts dynamic user-space library calls (such as malloc, printf, or strcmp provided by shared C libraries).
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout