How to check what's locking a file?

I noticed that sometimes Mail.app locks files. The lock itself allows for files to be moved to Trash, but doesn't allow Trash to be emptied. (Perhaps Trash should be renamed Thrash in this case)

Is there a way (via a terminal command or an app) to see which app locks the file and/or unlock the file without quitting the app?


Solution 1:

As Rabarberski says, lsof can be used to find any process that has the file open. Note that you need to run the program as root, i.e., using sudo, and that you can give the pathname to the file you're interested in as an argument, so there is no need for the grep invocation in the hint that Rabarberski points to. Also, if a process holds a lock on the file, you're supposed to be able to see that from the FD column in the lsof output. See the manual page for the details. (When I run sudo lsof on my machine, I see no locked files, so I won't guarantee that this works right on the Mac. sudo is after all a generic unix program, and conceivably some features don't work on OSX.)

You cannot unlock a file without killing the process that holds the lock. But you can remove it with rm from the command line.

Solution 2:

As others pointed out, lsof does the trick. To make the task even simpler, I suggest the (free) app "What's keeping me" (URL: http://www.hamsoftengineering.com/products/wkm/wkm.html) which is basically a frontend for lsof and has a few time-saving options.

Solution 3:

Apparently the lsof ("list of open files") terminal command can be used to do that: http://hints.macworld.com/article.php?story=20040121001144687