O'Reilly logo

Linux Server Hacks by Rob Flickenger

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #57. Checking On Open Files and Sockets with lsof

Easily see which files, directories, and sockets your running processes are holding open

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

root@mouse:~# umount /mnt
umount: /mnt: device is busy

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

root@mouse:~# lsof /mnt
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
bash 30951 rob cwd DIR 7,0 1024 2 /mnt

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:

root@mouse:~# lsof -p 30563 COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME inetd 30563 root cwd DIR 3,3 408 2 / inetd 30563 root rtd DIR 3,3 408 2 / inetd 30563 root txt REG 3,3 21432 39140 /usr/sbin/inetd inetd 30563 root mem REG 3,3 432647 11715 /lib/ld-2.2.3.so inetd 30563 root mem REG 3,3 4783716 11720 /lib/libc-2.2.3.so inetd 30563 root mem REG 3,3 19148 11708 /lib/libnss_db-2.2.so inetd 30563 root mem REG 3,3 238649 11728 /lib/libnss_files-2.2.3.so inetd 30563 root mem REG 3,3 483324 11710 /lib/libdb-3.1.so inetd 30563 root 0u CHR 1,3 647 /dev/null inetd 30563 root 1u CHR 1,3 647 /dev/null inetd 30563 root 2u CHR 1,3 647 /dev/null inetd 30563 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required