Wednesday, April 16, 2008

Identify the process that locks a file on Windows

I wanted to identify the process that locks a file on Windows, I am sure you know the feeling:

del ft*
The process cannot access the file because it is being used by another process.

There was an execellent article that described how one of my favorite tools procexp.exe from PsTools has a "Find handle or dll" (CTRL+F) that does the trick.
I think process explorer can only see local processes locking a file, it can not see if you have locked using a share for example. I have not tested it.
The same article also describes some possible solutions for command line based, I didnt have a need for that yet though:

Note: There is also a command-line tool named Handle from Windows Sysinternals that can display open handles for any process in the system. See: View Open Handles to a file or folder from the context menu from the Winhelponline.com Blog.

...

Once installed, reboot Windows and use the Oh.exe (Open Handles) command-line tool. For exact parameters, open Help and Support center and type-in OH. The following example shows how to find the Process(es) which have locked the file "INBOX.DBX".
Open a Command Prompt window and type:
oh inbox.dbx >C:\Output.txt

As for the oh.exe method it require reboot after windows 2003 resource kit installation, or you will see:
The system global flag `maintain object type lists' is not enabledfor this system. Please use `oh +otl' to enable it and then reboot.
But it looks very powerfull:

oh - Object handles dump -- built by: dnsrv_dev(v-smgum)
Copyright (c) Microsoft Corporation. All rights reserved.

OH [DUMP_OPTIONS ...]
OH [FLAGS_OPTIONS ...]
OH -c [COMPARE_OPTIONS ...] BEFORE_LOG AFTER_LOG

DUMP_OPTIONS are:

-p N - displays only open handles for process with ID of n. If not
specified perform a system wide dump.
-t TYPENAME - displays only open object names of specified type.
-o FILENAME - specifies the name of the file to write the output to.
-a includes objects with no name.
-s display summary information
-h display stack traces for handles (a process ID must be specified)
-u display only handles with no references in process memory
-v verbose mode (used for debugging oh)
NAME - displays only handles that contain the specified name.

No comments: