When a program fails without a clear error message, you need to see how it interacts with the kernel. strace shows each system call that a process makes, with its arguments and return value. You do not need the source code or a debug build. This post shows the basic use of strace and the options that you will use most.
Basic usage of strace
Pass strace the program and its arguments. This command runs ./example and traces it.
$ strace ./example
strace prints each system call while the program runs.
Common strace options
| Option | Function |
|---|---|
-e trace=<syscall> | Trace only the specified system calls. For example, -e trace=openat traces only openat. |
-f | Also trace child processes. |
-o <file> | Write the trace to a file. |
-s <size> | Set the maximum string size to print (default 32). |
-t | Prefix each line with the wall-clock time. |
-p <pid> | Attach to a running process. |
-c | Count the time, calls, and errors of each system call, and print a summary. |
For the full list, run man strace.
Example
This C program prints “Hello, World!”, then opens and closes a file.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
printf("Hello, World!\n");
int fd = open("strace_ex.c", O_RDONLY);
close(fd);
return 0;
}Compile the program and run it under strace. The output below omits the system calls of the dynamic linker (ld.so).
$ gcc strace_ex.c
$ strace ./a.out
execve("./a.out", ["./a.out"], 0x7ffea8a5a6b0 /* 16 vars */) = 0
brk(NULL) = 0x5607a950a000
arch_prctl(0x3001 /* ARCH_??? */, 0x7ffcb4547a10) = -1 EINVAL (Invalid argument)
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
...
write(1, "Hello, World!\n", 14Hello, World!
) = 14
openat(AT_FDCWD, "strace_ex.c", O_RDONLY) = 3
close(3) = 0
exit_group(0) = ?
+++ exited with 0 +++
Each line shows the system call, its arguments, and the return value after =. The last lines show the write system call from printf, and then the openat and close calls.