The utility lsof is a relatively new (well, compared to UNIX anyway) that has more options than even ls. These options provide for some extremely powerful capabilities, some of which we aim to illuminate here.
My favorite use for lsof is for networking: all sockets can be seen with the following options:
lsof -n -i
The -n option prevents lsof from being slowed down by a large number of DNS lookups, and the -i option returns all TCP/IP connections (with process numbers, user ids, file descriptor ids, and so on). To narrow it down, utilize options like the following – to list all SMTP connections, for example:
lsof -n -i :25
It is also possible to list only certain processes (such as process 25 and process 45):
lsof -n -p 25 -p 45
Alternately, the process can be selected by name:
lsof -n -c perl
However, suppose one wants to list all TCP/IP sockets held open by perl processes. The obvious choice does not work! This is because the options are combined together as an OR function; to combine them as an AND function (that is, all options must be satisfied) use the -a option – such as this:
lsof -a -n -c perl -i
This lists, as desired, all TCP/IP sockets held open by perl processes.
Another that might be useful in a security context is listing all files that are open but have no links to them: that is, they’ve been deleted, but one or more processes are keeping the file open, which means the file itself (and its blocks) are being preserved even though it appears to be deleted from the filesystem. To see these files, use this option:
The utility lsof is indeed very useful, and reading the man page for lsof is recommended.