10.5: Find out which program/process is locking a file

Nov 23, '09 07:30:00AM

Contributed by: boris42

Leopard only hintSometimes the trash won't be emptied, or a volume refuses to eject with a "file in use error." There have been hints on how to find that out in Terminal with lsof, which is not necessarily for the faint of heart.

Here is a nice Automator workflow that runs some AppleScript and shell commands and can be used in contextual Finder menu. So when a file is reported used, control-click on it and run the Automator workflow and see who is to blame. It will use user process space (no prompt for admin password), but will also revert to system process space if needed (prompting for the password). It will display the application/process that is using the file, and the account that started the program (could be you, could be root, could be another local user).

Open Automator with empty workflow, then add following actions, in this order:

  1. Get Selected Finder Items
  2. Sort Finder Items (you can omit that, if you want)
  3. Run AppleScript
In the body of the AppleScript action, replace the text that's there with the following:
on run {input, parameters}
repeat with aFile in input
  set theFile to quoted form of POSIX path of aFile
  set cmd1 to "lsof -t " & theFile
  try
    set thePid to do shell script cmd1
    on error number errorNumber
    try
      set thePid to ""
      set thePid to do shell script cmd1 with administrator privileges
    end try
  end try
  try
    if thePid is "" then
      set theMessage to theFile & " is not in use."
    else
      set cmd2 to "ps -o comm= -A " & thePid
      set theProgram to do shell script cmd2
      set cmd3 to "ps -o ruser= -A " & thePid
      set theOwnerName to do shell script cmd3
      set theMessage to theFile & " used by: " & thePid & " (" & theOwnerName & ")
" & theProgram
    end if
  end try
  display dialog theMessage buttons {"OK"}
end repeat
return theMessage
end run
Save it as a Finder Plug-in giving it a meaningful name, then quit Automator. Use it by Control-clicking the file that you want inspected (in Finder), then choose More » Automator » Find Buys (or whatever you named the plug-in).

[robg adds: I can't get this working on my 10.5 box, but it works fine for the author, so I'm running it under the assumption that I've done something to break it on my test machine. For me, the dialog appears empty, and Automator returns an error about not getting the selection from the Finder, even though I can display the value of the selected item within Automator.]

Comments (14)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20091104085622117