"strace" is a powerful command-line tool primarily used to trace system calls and signals on UNIX and UNIX-like systems (such as Linux). When diagnosing, analyzing, or debugging a running program, strace is an invaluable tool. The following outlines how to use strace:
1. Basic Usage
-
To trace system calls for a program, enter the strace command followed by the program name and its arguments in the command line. For example:
shellstrace lsThis will print all system calls made during the execution of the ls command.
2. Tracing Specific System Calls
-
If you are only interested in specific system calls, use the
-eoption to specify them. For example, to view all system calls related to file descriptor operations:shellstrace -e trace=file ls
3. Tracing Processes
-
strace can attach to a running process by providing its PID. For example:
shellstrace -p 1234This will trace the process with PID 1234.
4. Redirecting Output to a File
-
Use the
-ooption to redirect strace's output to a file for further analysis. For example:shellstrace -o output.txt lsThis writes the system calls of the ls command to output.txt.
5. Filtering Output
-
The
-eoption not only specifies which calls to trace but also filters output to show only relevant calls. For example:shellstrace -e open,close lsThis displays only the open and close system calls made by the ls command.
6. Tracing Child Processes
-
Use the
-foption to trace all child processes created by the main process. For example:shellstrace -f ./my_script.sh
7. Viewing System Call Statistics
-
To view system call statistics, use the
-coption. For example:shellstrace -c lsAfter execution, this displays statistics such as counts, time, and errors for all system calls.
8. Setting the Maximum String Length for Tracing
-
By default, strace truncates displayed strings. Use the
-soption to set the maximum string length. For example:shellstrace -s 1024 lsThis displays strings up to 1024 characters long.
Practical Example
Suppose you want to debug your program myapp, which has issues with certain file operations. Use strace to check for unexpected file read/write operations:
shellstrace -e trace=file -o strace_output.txt ./myapp
After execution, examine the strace_output.txt file. It may reveal access to unintended files or open system calls returning error codes indicating the root cause. Analyzing this output helps pinpoint the exact problem location and guide code modifications.
The above covers the basic usage and advanced options of strace to help you debug and understand program behavior more effectively.