Determine if a file (dll / exe) is locked or not by a process or library

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

How can we achieve this programmatically using the WIN API (C / C ++ feature)? In fact, when we are performing some software update process, some other process may use a library that will temporarily perform the update operation.

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

+2


source to share


5 answers


You can try opening the file yourself for exclusive access. If any other process opens them, it should fail.



+4


source


I don't think it is possible to define processes without writing a driver. Fortunately, Rusinovich's Handle Tool includes such a driver; I suggest you run this tool.



+1


source


If you don't need to know which processes are using this file, you can simply open the file for exclusive access using CreateFile

.

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

      

+1


source


In Windows, the file is not "locked" or "unlocked". If the file is open, the sharing mode specified when you open it determines whether, and under what circumstances, other attempts to open the file will succeed.

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

Once you've determined what level of exclusion you think is "locked", you can simply try to open each file with the appropriate access and see if it fails with ERROR_SHARING_VIOLATION or not.

+1


source


It seems to me that the windows API provides EnumProcesses () to easily get a list of active processIDs and EnumProcessModules to get a list of module descriptors (which, if the EXE and DLL are associated with it) for each process; finally, GetModuleFileNameEx () provides the full path and filename of the loaded module.

This way, you can easily iterate over all the DLL names loaded and at least know which process was holding them if you find a problem - and possibly terminate the process automatically.

0


source







All Articles