Ubuntu: Using strace to get a view into file and network activity of a process

strace is a handy utility for tracing system, file, and network calls on a Linux system.  It can produce trace output for either an already running process, or it can create a new process.

Some of the most common troubleshooting scenarios are needing to isolate either the network or file system activity of a process.  For example to determine whether an application was attempting to reaching out to a server on the expected port, or to understand why a startup configuration file was not being read from the expected directory.

Tracing new process

Tracing a new process just requires that you put the desired process and its arguments at the end of the strace command.  For example, to trace the calls required to do a listing of the /tmp folder:

# strace -r -f ls /tmp

Or to trace all the calls from a URL fetch of the Google home page:

# strace -r -f wget -q https://www.google.com

The ‘-r’ switch prints an elapsed time by each call, and the ‘-f’ traces any forked processes that might be created (common for network servers).

Tracing by attaching to existing process

Attaching to an existing process requires that you know the process id (pid).  The easiest way to determine this is to run ‘ps -ef’ and find the root process id of the application in question.  If you would rather find the process id by the port it is listening on you can use ‘lsof -i -P | grep LISTEN’.

Once this is determined, you can run strace like:

# strace -r -f -p <pid>

This will most likely result in a large amount of output to the screen because we did not use an expression filter, so CTRL-C out.  In the following sections, we will apply filters that limit the output.

Tracing file system activity

If you want to trace all file related calls (open/close/read/write), then:

# strace -r -f -e trace=file -p <pid>

But this can often be too much, and you may just want to see what ‘open’ attempts are made which can tell you why a configuration file is not being read, or what directory it might actually be attempting to access:

# strace -r -f -e trace=open -p <pid>

If this is still too much, you can also output the trace to a file, and do a search/tail/grep on strace.log to identify only those filenames that you want to monitor:

# strace -r -f -e trace=open -o strace.log -p <pid>

Tracing network activity

In our first example, we traced all the system calls for a URL retrieval of the Google home page.  If we just wanted to trace the network related calls:

# strace -r -f -e trace=network wget -q https://www.google.com






7 Strace Examples to Debug the Execution of a Program in Linux

Linux application/script debugging with ‘strace’