tags:

views:

95

answers:

5

I need a script to identify the files opened a particular process on linux

To identify fd :

>cd /proc/<PID>/fd; ls |wc –l  

I expect to see a list of numbers which is the list of files descriptors' number using in the process. Please show me how to see all the files using in that process. Thanks.

A: 
lsof | grep processName
Macmade
+1  A: 

You need lsof. To get the PID of the application which opened foo.txt:

lsof | grep foo.txt | awk -F\  '{print $2}'

or what Macmede said to do the opposite (list files opened by a process).

Tomislav Nakic-Alfirevic
ohThanks! let me try
aladine
That will list the processes using a file. I think he wants the files used by a process... So type the process name instead of the file name...
Macmade
Correct, I updated the answer.
Tomislav Nakic-Alfirevic
+1  A: 
lsof -p <pid number here> | wc -l

if you don't have lsof, you can do roughly the same using just /proc

eg

$ pid=1825
$ ls -1 /proc/$pid/fd/*
$ awk '!/\[/&&$6{_[$6]++}END{for(i in _)print i}' /proc/$pid/maps
ghostdog74
+1  A: 

The command you probably want to use is lsof. This is a better idea than digging in /proc, since the command is a more clear and a more stable way to get system information.

lsof -p pid

However, if you're interested in /proc stuff, you may notice that files /proc/<pid>/fd/x is a symlink to the file it's associated with. You can read the symlink value with readlink command. For example, this shows the terminal stdin is bound to:

$ readlink /proc/self/fd/0
/dev/pts/43

or, to get all files for some process,

ls /proc/<pid>/fd/* | xargs -L 1 readlink
Pavel Shved
A: 

While lsof is nice you can just do:

ls -l /proc/pidoftheproces/fd
nos