Using strace in Linux: Usage and Examples
One of the things that we always leave aside are the bases, this time I wanted to make a post about something that I think is really useful, even if you are a devops engineer, SRE or sysadmin.
What is strace? strace is a powerful command-line tool for tracing system calls and signals made between a process and the kernel in Linux. It allows users to identify and debug errors in programs by displaying all the system calls and signals made by the process.
How to use strace? To use strace in Linux, first, ensure it is installed on your system by typing the following command:
sudo apt-get install strace
To trace a program using strace, type the following command in the terminal:
strace [OPTIONS] command
Where [OPTIONS]
are the various options that you can use with strace, and command
is the program you want to trace.
Examples of using strace
1.- Trace the ls
command and display all system calls:
strace ls
Output:
execve("/bin/ls", ["ls"], 0x7ffcde7e6ba0 /* 75 vars */) = 0
brk(NULL) = 0x5583290fc000
access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
...
2.- Trace the ping
command and filter the output to only show read
and write
system calls:
strace -e read,write ping google.com
Output:
read(4, "\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37"..., 128) = 56
write(4, "\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37"..., 56) = 56
...
3.- Trace a running process using its PID:
strace -p [PID]
Where [PID]
is the process ID of the running process you want to trace.
Output:
read(3, "GET / HTTP/1.1\r\nHost: example.co"..., 1024) = 59
write(3, "HTTP/1.1 200 OK\r\nServer: nginx/"..., 191) = 191
...
4.- Trace a command and output results to a file:
strace -o output.txt ls -la
This will trace the ls
command and save the output to a file called output.txt
.
Output (in the output.txt
file):
execve("/bin/ls", ["ls", "-la"], 0x7ffe358f4358 /* 55 vars */) = 0
brk(NULL) = 0x55d54e1f6000
access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
...
Conclusion
strace is an essential tool for diagnosing and debugging errors in Linux. By tracing the system calls and signals made by a program, users can analyze its behavior, identify performance issues, and gain a deeper understanding of how it interacts with the kernel. The examples provided in this article are just a few of the many ways that strace can be used to improve your understanding of how Linux works. Whether you are a developer, system administrator, or simply an enthusiast, strace is a valuable addition to your Linux toolkit.