Thursday, January 9, 2014

Does lsof on Mac OS X display information about advisory file locks?

On many Unix systems, the marvelous lsof utility provides vast amounts of information about what your processes are doing.

One part of that information is supposed to include details about the locks that are held on the open files:

The mode character is followed by one of these lock characters, describing the type of lock applied to the file:

N for a Solaris NFS lock of unknown type;
r for read lock on part of the file;
R for a read lock on the entire file;
w for a write lock on part of the file;
W for a write lock on the entire file;
u for a read and write lock of any length;
U for a lock of unknown type;
x for an SCO OpenServer Xenix lock on part of the file;
X for an SCO OpenServer Xenix lock on the entire file;
space if there is no lock.

On Linux, at least, this works great; I see the lock characters as I expect.

On Mac OS X, though, I never see those lock characters.

When I look at a recent copy of the FAQ, I see a note about NEXTSTEP:

12.0 NEXTSTEP and OPENSTEP Problems

12.1 Why can't lsof report on 3.1 lockf() or fcntl(F_SETLK) locks?

Lsof has code to test for locks defined with lockf() or fcntl(F_SETLK) under NEXTSTEP 3.1, but that code has never been tested. I couldn't test it, because my NEXTSTEP 3.1 lockf() and fcntl(F_SETLK) functions return "Invalid argument" every way I have tried to invoke them.

I'm not sure if this section applies to the Mac OS X version of lsof, or not.

For yucks, I tried looking at the source, and it sure looks like the implementation retrieves the access mode and turns it into 'r', 'w', or 'u', appropriately, and also retrieves the file size and type information, but there doesn't appear to be any code to fetch the lock information.

Searching the web for more information found a random web page or two where others seemed to say that they couldn't get this feature of lsof to work on their Mac.

And, of course, I can't get it to work on my Mac (I appear to be running lsof 4.82 on Mac OS X 10.6.8, if that's relevant).

Does anybody know? Does this work?

2 comments:

  1. UPDATE: After some more study (and some reading of kernel sources...), my colleague Jeff showed me that "lsof -F pGn +fG -p NNN" works for displaying advisory file locks, provided that you interpret advisory file locks using the hexadecimal values of the FILE-FLAGS field.

    ReplyDelete
  2. To check for locks on a particular file, I'm getting nicer output with "sudo lsof +fg MY_LOCK_FILE". This shows labeled columns, including FILE-FLAG column with fcntl locks listed as "W,0x4000". The first value is definitely a write lock on the entire file; the second might be a non-blocking lock.

    To see these flags as their "raw" (vs. mnemonic) values, use +fG instead: "sudo lsof +fG MY_LOCK_FILE"

    ReplyDelete