14

The files opened by a process can be found with this command:

ls -l /proc/PID/fd

Is there any way that can be done in a more interactive way like tail, auto-refreshing every x seconds?

Matthias Braun
  • 225
  • 1
  • 8
Frankie
  • 429
  • 1
  • 6
  • 20

4 Answers4

19

Try the nice watch command:

watch -n 10 ls -l /proc/$$/fd

You could use an old school while loop:

while:
do
 ls -l /proc/$$/fd
 sleep 10
done

watch is in the procps package on Debian-based systems and the procps RPM on Red Hat-derived systems.

vidarlo
  • 6,654
  • 2
  • 18
  • 31
gm3dmo
  • 10,057
  • 1
  • 42
  • 36
  • 1
    sleep itself can be used as condition in while loop, so your example can be written more elegantly like this: while sleep 10; do ls -l /proc/$$/fd; done – ipozgaj Jan 06 '11 at 12:55
14

If you want to see each file as it is being opened, you can filter that with strace. For example:

strace -p _pid_of_app_ -e trace=open,close
Evgeny
  • 599
  • 5
  • 10
  • 6
    This _really_ is the best answer. I'd recommend the flags `-y` and `-f` if you're attempting to debug something running in a shell. Just pass the shell PID in and `-f` will follow any forks. – Aea Sep 25 '17 at 22:42
6

You could combine lsofand watch.

For example watch "lsof -p 1234" will give you a list of all open files of pid 1234 every 2 seconds. You could change some parameters to meet your needs.

Christian
  • 4,703
  • 2
  • 24
  • 27
  • it will not give a list EVERY 2 seconds. The parameter -r 2 is missing for that to work! -p is the PID. The answer is very poor! – mahatmanich Aug 16 '17 at 06:51
  • 2
    Nice, wasn't aware of the `-r` option for `lsof`. Therefore I used `watch` to execute `lsof` every two seconds. – Christian Aug 16 '17 at 08:57
1

I created a bash file where I was writing the output of the command to a file. File was generated on the basis current date. Here I am counting number of open files.

#!/bin/bash
while :
do
 cd /proc/<PID>/fd
 today=$(date +"%m-%d-%Y")
 filename="/tmp/${today}.txt"
 ls -l | wc -l >> "${filename}"
 sleep 10
done