Skip to main content

Finding all files a process is opening in GNU/Linux by tracing system calls

Sometimes while debugging, we need to find all the files a process is opening for reading data from to get a hint about the program's design and workflow. Otherwise we want to follow the lengthy route of reading the source code of the program, we could leverage the powerful system call tracing tool strace to get the job done fairly easily.


strace binary comes with the strace package; so you need to install it first (if not done already):

% dpkg -S "$(command -v strace)"
strace: /usr/bin/strace

The above snippet is from my dpkg packaging based system, although the same should be true for rpm packaging based systems.

strace binary is mostly used for tracing system calls and signals. As we're planning to get the files opened by a process, we're looking for the open(2) call specifically.

Trace open(2):

Let's assume the program we want to check is named foobar and we need to pass --name spamegg argument to it i.e. from the shell we would run it as:

foobar --name spamegg

Now to trace the syscalls made by the program we need to run it as an argument to strace, with necessary arguments e.g.:

strace foobar --name spamegg

As the above would trace all system calls foobar is making, not just open(), let's narrow down the traced calls to just open():

strace -e trace=open foobar --name spamegg

-e option lets us to apply filerting, here we're trace-ing only the open call. -e open is a shorthand for -e trace=open, so we can also write:

strace -e open foobar --name spamegg

Now we'll get all the files opened by foobar.

If you want to track all the child processes of foobar as well, you need to issue the -f option:

strace -f -e open foobar --name spamegg

or as strace allows us to express multiple command line options combinedly:

strace -fe open foobar --name spamegg

You can also trace multiple calls by comma separating them e.g.:

strace -fe open,write foobar --name spamegg

You can even trace a process that has already been started by passing the PID (Process ID) with the -p option:

strace -fe open,write -p <PID>

So for example, if the PID is 1234:

strace -fe open,write -p 1234

strace is a powerful tool when comes to debugging, the above is just the tip of the iceberg.

As always check out the man page (man strace) to get more ideas.

Happy debugging!


Comments powered by Disqus