The power of “lsof”

One great command to add to your arsenal is the “lsof” command. This command prints out all open files in Linux.

lsof can be used to help resolve issues like:

  • Can’t unmount device because it is busy; even if you believe it’s not busy.
    umount: /mountpoint: device is busy
  • A process is using a file but you have no idea which process
  • To view a list of active connections (netstat works better for this) and which program and PID (Process ID) is using this socket.

To successfully unmount a device which still complains about being in use simply run the following command:

# lsof | grep “/mountpoint”

This command returns a list of processes and associated PID’s and the user which has that directory or files open. Look for files (usually marked with “REG”) which will allow you to locate the service or program with the file open. Stop this service or at the very extreme kill -9 that process. (A funny video about kill -9)

To search for a file which is in use simply use an alteration of the command above:

# lsof | grep “openfile”

This allows you to locate the process and user using that file.

To view a list of active connections run this command:

# lsof | grep “IPv4”

This returns a list of all open IPv4 connections.

Also be aware that the “lsof” command can take quite some time to run on servers with very large file counts open (Oracle Servers, Web Servers) so please be patient. It’s not uncommon for the lsof command to take about 2-4 seconds to run.

Happy Linuxing!

Leave a Reply

Your email address will not be published / Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.