Checking On Open Files and Sockets with lsof

Have you ever tried to umount a filesystem, only to find that some process was still using it?


To quickly hunt down what processes are still using /mnt, try the lsof tool:


Ah, apparently rob is cd'd to /mnt (since his bash process has it set as its cwd). lsof will list all open files, directories, libraries, sockets, and devices associated with a particular process. In the above example, we specified a mount point and had lsof show us the associated processes. To do the reverse (show files associated with a PID), use the -p switch:


If you'd rather specify the process by name, use -c:


You can also specify special devices on the command line. For example, let's see what the user on pts/0 is up to:


If you need to specify multiple switches, they are ORed with each other by default. To require all switches (that is, to AND them) include the -a flag on each switch you want to AND. For example, to see all of the open files associated with vi processes that rob is running, try this:


If you'd like to examine open sockets and their associated processes (like a netstat -p), try the -i switch:


Note that you must be root to run lsof for many functions, including retrieving open socket information. lsof is a complex and very flexible tool, giving you as much (or as little) detail as you need about what files are in use by every running process on your system.

No comments:

Post a Comment