tags:

views:

303

answers:

6

How can I find which processes have a specific file opened, and their open, access and share modes? Additionally, is it possible to change these values for a process? Or is it even possible to open a file for reading if it is already opened for exclusive access by another process?

Please note that I don't want to invalidate the handle of the process having the file opened. I just want to be able to access the file (if possible).

(I'm mainly asking about Windows, but solutions for other platforms are welcome, since they contribute to the community's knowledge.)

Edit: I found some answers for my first question here and there.

Edit 2: Thanks everybody for the tools you mentioned, but I am mainly looking for programmatical techniques (e.g. using Win32 APIs).

+4  A: 

Process Monitor

Process Explorer

Mitch Wheat
Thanks for your help @Mitch. Please accept my apology for not mentioning "programmatically" earlier.
Hosam Aly
@Hosam Aly: hey no problem. My comment probably sounded a bit severe, which it wasn't meant to.
Mitch Wheat
+2  A: 

There is an utility called Unlocker which tells you which process has got the lock on a resource .

Kapilg
This is actually on my "must-have" list for Windows... I find that whether I want to or not, I end up installing it well within a week of installing Windows.
Matthew Scharley
+3  A: 

For windows, I know about a Tool from Sysinternal (www.sysinternals.com): handle.exe.

+1  A: 

For unix you can use fuser:

lnx0:i386_linux26> fuser -v a.cpp

                     USER        PID ACCESS COMMAND
a.cpp                nabcdefg    3952 f....  less
Nathan Fellman
+1  A: 

It's the lsof command under Linux systems.

Drejc
A: 

Im not sure if there is a way to do exactly what you want but I do know that using System.Diagnostics.Process class (at least in .Net) you can open processes and watch for certain properties:

System.Diagnostics.Process[] procArray = System.Diagnostics.Process.GetProcessesByName("notepad");
foreach (System.Diagnostics.Process proc in procArray) {
    //do something with the process...
}

Look around the Process class, maybe there is a property or collection to get the data you are looking for.

Gustavo Rubio
I'm pretty certain you can't check for file locks via this route.
Marc Gravell
Maybe using the Win32 api directly through P/Invokes and getting the process handle with .Net?
Gustavo Rubio
Why was the commmend voted down? I just don't understand it sometimes...
Gustavo Rubio