Skip to main content

Finding all files a process is opening in GNU/Linux

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 you want to follow the lengthy route of reading the source code of the program, you could leverage the powerful system call tracer tool strace to get the job done fairly easily.

Background:

strace binary comes with the strace package:

% 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 as well, we need to issue the -f option:

strace -f -e open foobar --name spamegg

or 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

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

Comments powered by Disqus