The strace is the tool that helps in debugging issues by tracing system calls executed by a program. It is handy when you want to see how the program interacts with the operating system, like what system calls are executed in what order.
This simple yet very powerful tool is available for almost all the Linux based operating systems and can be used to debug a large number of programs.
1. Command Usage
Let's see how we can use strace command to trace the execution of a program.
In the simplest form, any command can follow strace. It will list a whole lot of system calls. Not all of it would make sence at first, but if you're really looking for something particular, then you should be able to figure something out of this output.
Lets see the system calls trace for simple ls command.
[email protected] ~ $ strace ls
This output shows the first few lines for strace command. The rest of the output is truncated.
The above part of the output shows the write system call where it outputs to STDOUT the current directory's listing. Following image shows the listing of the directoy by ls command (without strace).
[email protected] ~ $ ls
1.1 Find configuration file read by program
One use of strace (Except debugging some problem) is that you can find out which configuration files are read by a program. For example,
[email protected] ~ $ strace php 2>&1 | grep php.ini
1.2 Trace specific system call
The -e option to strace command can be used to display certain system calls only (for example, open, write etc.)
Lets trace only 'open' system call for cat command.
[email protected] ~ $ strace -e open cat dead.letter
1.3 Stracing a process
The strace command can not only be used on the commands, but also on the running processes with -p option.
[email protected] ~ $ sudo strace -p 1846
1.4 Statistical summary of strace
The summary of the system calls, time of execution, errors etc. can be displayed in a neat manner with -c option:
[email protected] ~ $ strace -c ls
1.5 Saving output
The output of strace command can be saved into a file with -o option.
[email protected] ~ $ sudo strace -o process_strace -p 3229
The above command is run with sudo as it will display error in case the user ID does not match with the process owner.
1.6 Displaying timestamp
The timestamp can be displayed before each output line with -t option.
[email protected] ~ $ strace -t ls
1.7 The Finer timestamp
The -tt option displays timestamp followed by microsecond.
[email protected] ~ $ strace -tt ls
The -ttt displays microseconds like above, but instead of printing surrent time, it displays the number of seconds since the epoch.
[email protected] ~ $ strace -ttt ls
1.8 Relative Time
The -r option displays the relative timestamp between the system calls.
[email protected] ~ $ strace -r ls