Read the Manual: lsof

Like ls, but it’s about open files instead of files in a directory. Neat!

Assumed audience: People interested in learning how the command lines tools on their computer work.

It’s Thursday! That means it’s Read the Manual time! This week, lsof: a tool I used to solve a problem on Saturday. lsof is one of those tools I only learned about sometime this year, for solving exactly the same problem I solved Saturday: Why will this volume not unmount?”

man lsof says it:

Lsof… lists file information about files opened by processes for the following UNIX dialects:

  • Apple Darwin 9 and Mac OS X 10.567
  • FreeBSD 8.234, 9.0 and 1012.0 for AMD64-based systems
  • Linux 2.1.72 and above for x86-based systems
  • Solaris 9, 10 and 11

(Yes, Apple Darwin 9 and Mac OS X 10.[567] 😂 And FreeBSD with those []-based versions, too. No, I have no idea why those are that way; feel free to chime in and tell me! It is neat that it works on Linux and… Solaris? Now there’s a name I’ve not heard in long time.)

The next bit was a revelation when I learned about lsof:

An open file may be a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.)

What that means in practice is that you can use lsof to figure out all sorts of interesting things. What program is interfering with your editor autosave? lsof path/to/file. What process opened port 4200? lsof -i http://localhost:4200. And so on. Linux pipes? Check.

The way I used it this past weekend was to figure out why macOS would not let me eject an external volume. Again, per the man page:

A specific file or all the files in a file system may be selected by path.

I could (and did!) just sudo lsof "/Volumes/Kuat RZ-1" to find out.

The answer: Spotlight was indexing files newly downloaded to this SSD to back them up from Adobe’s cloud storage. I turned off Spotlight indexing for the drive, and killed the relevant Spotlight process — it just starts back up, but was no longer opening files on the drive.

There are, perhaps unsurprisingly, tons of flags for this. I am not even going to try to list them all — suffice it to say there’s probably an option if you need it for any of those kinds of files”. This is one of the interesting consequences of everything is a file” on *nixes! It was really only sometime in 2023 or 2024 that I really started to grok everything downstream of that, like sockets are just file descriptors” — a fact I had known in a brute sense for a long time, but which I had never internalized any of the consequences of. It’s neat!

There are also tons of combinations of options with lsof: you can negate the search pattern you give it, for example — “show me files opened by a user not me would be something like lsof -u ^(id -u), using the id command to get my user ID. (I’ll do id next week!)