0

I know that I can use lsof to track files opened by running processes, process groups, users, and those open in specific directories, among other example. However I am curious to see if I can trap files that were opened by a program that is not always running, but runs only for a limited amount of time, such as a bash script or a Ruby program.

For instance, imagine I can run my Ruby tests by doing rspec in my Rails directory. How can I get a list of ALL files open by rspec?

In other words, how can make lsof trap open files from a process in real time? Visually, it make look like lsof rspec, where lsof execs rspec and records all open files.

codeforester
  • 39,467
  • 16
  • 112
  • 140
n_x_l
  • 1,552
  • 3
  • 17
  • 34

1 Answers1

2

I think you may be looking for the strace program, which can trace and log system calls. For example, I can ask for a list of files opened by the grep command like this:

strace -e trace=open,openat grep something M* > /dev/null

The -e trace=open,openat option tells strace that we're only interested in those two system calls.

I've redirected the output of grep to /dev/null here to avoid cluttering the output; you could also send the output of strace to a file using the -o option.

Assuming I have the files MANIFEST.in, MODULE_GUIDELINES.md, and Makefile in my local directory, this might produce output like:

openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3      
openat(AT_FDCWD, "/lib64/libpcre.so.1", O_RDONLY|O_CLOEXEC) = 3   
openat(AT_FDCWD, "/lib64/libc.so.6", O_RDONLY|O_CLOEXEC) = 3      
openat(AT_FDCWD, "/lib64/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3    
open("/usr/lib64/gconv/gconv-modules.cache", O_RDONLY) = 3        
openat(AT_FDCWD, "Makefile", O_RDONLY|O_NOCTTY) = 3               
openat(AT_FDCWD, "MANIFEST.in", O_RDONLY|O_NOCTTY) = 3            
openat(AT_FDCWD, "MODULE_GUIDELINES.md", O_RDONLY|O_NOCTTY) = 3   
+++ exited with 0 +++

You can see here both the shared libraries opened when running grep as well as the files that were opened by grep itself.

You can read more in the strace man page.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • Indeed. I am using Mac OS X so I will have to give DTrace a try. Thanks for your answer. – n_x_l Jun 24 '18 at 15:40