strace - Linux


Overview

strace is a powerful diagnostic, instructional, and debugging tool primarily used in Linux environments. It displays the system calls made by a process and the signals received by the process. This command is most beneficial for software developers, system administrators, or anyone who needs to understand how applications interact with the kernel.

Syntax

The basic syntax of the strace command is:

strace [options] [command]

This syntax can include a variety of options and can be used to trace a running process or start and trace a new process by specifying the command.

Options/Flags

  • -c: Counts time, calls, and errors for each system call and reports a summary on program exit.
  • -d: Enables debug output to stderr.
  • -e trace=<set>: Trace only a specified set of system calls. For example, -e trace=open,close traces only open and close calls.
  • -f: Trace child processes as they are created by currently traced processes due to the fork system call.
  • -o <filename>: Output the trace to a file rather than to stderr.
  • -p <pid>: Attach strace to the process with the specified process ID (PID).
  • -s <size>: Specifies the maximum string size to print (default is 32). Increase this to see more data.
  • -t: Prefix each line of the trace with the time of day.
  • -v: Print all environment variables and expanded arguments for calls.

Examples

  1. Basic Trace:
    Trace all system calls made by the ls command:

    strace ls
    
  2. Output to File:
    Trace the ls command and output the results to a file:

    strace -o trace.txt ls
    
  3. Trace Specific System Calls:
    Trace only open and close system calls of the ls command:

    strace -e trace=open,close ls
    
  4. Trace a Running Process:
    Attach strace to a running process with PID 1234:

    strace -p 1234
    

Common Issues

  • Permission Denied: Running strace may require elevated permissions. If you encounter a permission issue, try running it with sudo.
  • High Output Volume: strace can generate a lot of output quickly; use the -o option to direct output to a file for easier analysis.
  • Performance Impact: The tracing process can significantly impact system performance. Use it judiciously on production systems.

Integration

strace can be combined with other Linux tools for enhanced debugging:

  • Using with grep:

    strace ls 2>&1 | grep open
    

    This command traces system calls made by ls and filters for open calls.

  • Automated Analysis:
    Combine strace output with a script to analyze frequent system calls:

    strace -c ls > output.txt
    
  • ltrace: Tracks library calls in user-space programs.
  • gdb: GNU debugger that can inspect what is happening inside a running program more comprehensively.
  • tcpdump: For network-related system calls.

For more detailed information, visit the official man page (man strace) or the strace GitHub repository.