lsof is a very useful Linux command, which can be used to report a list of all open files and the processes that opened them. lsof is very useful in debugging because files in the Linux/Unix system include disk files, named pipes, network sockets and devices opened by all processes. lsof name comes from “list open files”.
What you do when you don’t have lsof, but you need to do similar checks for open files. fuser is another useful Linux command that can be used to show which processes are using a specified file, file system, or unix socket. It is very useful in some cases and not very useful in some other cases.
There are also other ways how to check open file without lsof. Those might come handy if you use a Linux system which does not have lsof command, and you can’t easily add it (for example embedded Linux systems or Linux servers you are not allowed to modify).
You can use ls command to get information on open files from /proc/ file system. When you know the process id of your program (you can find it with ps and pgrep commands), you can run the following command (replace
[process id] with your process number) to see the open files:
ls -l /proc/[process id]/fd
You can list all the files opened by all processes in the system with following command:
ls -l /proc/*/fd
For debugging your own programs you can write following kind of script that takes your program name as argument and prints files opened by it (works only in cases where there is only one executable with the name you give as argument):
ls -l /proc/`pgrep `/fs
This was today’s Linux tip.