views:

400

answers:

5

I'am planning to write a sample program which identifies a file (a dll file) locked by / used by some process.

How can we achieve this programmatically using WIN API (a C/C++ function)? Actually, when we are performing some software upgrade process some other process might be using the library which will interim fail the upgrade operation.

The best example I would like to bring here is the Unlocker tool which lists all the process/dll which are using a particular file.

+1  A: 

I don't think it is possible to determine the processes without writing a driver. Fortunately, Russinovich's Handle tool includes such a driver; I suggest that you run this tool.

Martin v. Löwis
i am not interested in which process locks the file, rather am interested in if the file is locked or not. an API which return a values whether a file is locked or not would be much better something like "getFileLockStatus(filename)"
Venkat
I fail to see the point. If you have an API that can tell you exactly which processes have locked a file, then you have an API that can tell you simply if a file is locked or not. It can't be hard to write a short function that returns a boolean if there isn't one built in.
Matthew Scharley
+3  A: 

You could try opening the file(s) yourself for exclusive access. If any other process has them open, this should fail.

Timo Geusch
+1  A: 

If you don't need to know which processes use the file in question, you can simply open the file for exclusive access using CreateFile.

::CreateFile(filename, 0, 0, 0, OPEN_EXISTING, 0, 0);
avakar
A: 

In Windows, a file is not 'locked' or 'unlocked'. If a file is open, the share mode specified when opening it determines if and under what circumstances other attempts to open the file succeed.

If the FILE_SHARE_NONE flag is specified, then the file is completely locked, and under no circumstances will any other attempt to open the file succeed. If FILE_SHARE_READ was specified, attempts to open the file with GENERIC_READ access will succeed, but GENERIC_WRITE will fail, for example. FILE_SHARE_WRITE allows other handles open for write access, and FILE_SHARE_DELETE the same for deletion.

Once you've decided which level of exclusion you consider to mean 'locked', you can just try to open each file with the relevant access and see if it fails with ERROR_SHARING_VIOLATION or not.

anelson
A: 

Seems to me the windows API provides EnumProcesses() to easily get a list of active processID and EnumProcessModules to get a list of module handles (that if EXE and DLL's associated with it) for each process; finally GetModuleFileNameEx() gives you the full path and filename of the loaded module.

Thus you could easily iterate through all the loaded DLL names and at least know which process was holding them if you detected a problem - and possibly automatically end that process.

Elemental