Strace and Ltrace: Trace System and Library Calls
Introduction
strace is a debugging tool on Linux used to monitor system calls made by a program and all the signals it receives, similar to the “truss” tool on other Unix systems. It’s made possible through a Linux kernel feature called ptrace.
The most common use is to launch a program using strace, which displays a list of system calls made by the program. This is useful when a program continually crashes or doesn’t behave as expected. For example, using strace can reveal that the program is trying to access a file that doesn’t exist or can’t be read.
Another use is to use the -p option to attach it to a running program. This is useful when a program stops responding, and can reveal, for example, that the process is blocked waiting to make a network connection.
Since strace only details system calls, it can’t be used as a code debugger like Gdb. However, it remains simpler to use than a code debugger and is an extremely useful tool for system administrators.
In this documentation, I won’t discuss ltrace much because its usage is quite similar to strace.
Installation
Debian
To install on Debian:
|
|
Red Hat
|
|
Usage
For example, if we want to debug an issue with an Apache server:
|
|
The -f option of strace traces child processes as they are created by currently traced processes following the fork system call.
All you need to do is analyze the lines to see the issue. This can be tedious depending on the number of lines, but generally the information about your problem is here.
Redirecting Output to a File
If we want to redirect all of strace’s output (initially on error output) to a file using the -o option:
|
|
Working with Standard Output
As you now know, strace works on error output, so if you want to work on it with grep or other commands on-the-fly (without redirecting to a file), you’ll need to use redirection:
|
|
Working with Specific Kernel Calls Only
If you want to get only open and access type calls, for example:
|
|
Here are some examples of system calls you can try:
|
|
Increasing the Number of Characters to Display
You can increase the display size using the -s option followed by the desired size (5000 for example):
|
|
Attaching to an Existing PID
If we want to trace a process that’s already running, it’s possible. To do this, simply use the -p argument:
|
|
Getting Statistics
If you want to get statistics, we’ll use the -c option:
|
|
Detecting Network Problems
If, for example, you only want to work on a network layer, here’s the solution:
|
|
Example
Here’s an example of this command with some explanations to help you get started with a ’ls’ command:
|
|
Resources
Last updated 20 Jan 2012, 10:32 +0200.