- What Win32 API can be used to find the process that has a given file open?
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged winapi api file or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Как вы узнаете, какой процесс удерживает файл открытым в Windows?
- How To Know Which Process is Using a File or Folder in Windows
- Resource Monitor
- Process Explorer
- My Take
- Gizmo’s Freeware
- Login / Register
- Main menu
- How to Find Out Which Windows Process is Using a File
- How to find out what program is using a file
- How to find out which handle or DLL is using a file
- How do you find what process is holding a file open in Windows?
- 16 Answers 16
What Win32 API can be used to find the process that has a given file open?
If I read or write to a file and receive a 33 or 32 error, I would like to log a message containing the name of the other process(es) that have the file opened. There must be a Win32 API I could use to get this info. Process Explorer displays it. Of course, Process Explorer also has info about all processes in memory. I’d prefer to find the culprit without interrogating all processes.
2 Answers 2
This seems to do what you want.
obviously it uses some hidden API such as NtQueryInformationProcess .
The Handle program from SysInternals does this as well, but I’m not sure how. I don’t think there is a single documented API to do this. I think you have to iterate over the processes, enumerate each of the handles in the process, and then determine the filename associated with that handle.
Not the answer you’re looking for? Browse other questions tagged winapi api file or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Как вы узнаете, какой процесс удерживает файл открытым в Windows?
Одна вещь, которая раздражает меня в Windows, это старая ошибка нарушения общего доступа. Часто вы не можете определить, что держит его открытым. Обычно это просто редактор или исследователь, просто указывающий на соответствующий каталог, но иногда мне приходилось прибегать к перезагрузке компьютера.
Любые предложения о том, как найти виновника?
Я имел успех с Sysinternals Process Explorer . С помощью этого вы можете искать, чтобы найти, какой процесс (ы) имеют открытый файл, и вы можете использовать его, чтобы закрыть дескриптор (ы), если хотите. Конечно, безопаснее закрыть весь процесс. Проявляйте осторожность и рассудительность.
Чтобы найти конкретный файл, используйте пункт меню « Find->Find Handle or DLL. Введите» в части пути к файлу. Список процессов появится ниже.
Если вы предпочитаете командную строку, в комплект Sysinternals входит инструмент Handle командной строки , в котором перечислены открытые дескрипторы. Несколько примеров о том, как его использовать:
- c:\Program Files\SysinternalsSuite>handle.exe |findstr /i e:\ — найти все файлы, открытые с диска E:
- c:\Program Files\SysinternalsSuite>handle.exe |findstr /i file-or-path-in-question
Для этого вы можете использовать Resource Monitor, который встроен в Windows 7, 8 и 10.
- Откройте Resource Monitor , который можно найти
- Выполнив поиск Resource Monitor или resmon.exe в меню «Пуск», или
- Как кнопка на вкладке « Производительность » в вашем диспетчере задач
- Перейти на вкладку CPU
- Используйте поле поиска в разделе « Связанные дескрипторы »
- Смотрите синюю стрелку на снимке экрана ниже
Найдя дескриптор, вы можете определить процесс, посмотрев на столбец «Изображение» и / или «PID».
Затем вы можете попытаться закрыть приложение, как обычно, или, если это невозможно, просто щелкнуть правой кнопкой мыши по дескриптору и завершить процесс прямо оттуда. Очень просто!
Просто будьте очень осторожны с закрывающимися ручками; это даже более опасно, чем вы думаете, из-за повторного использования дескриптора — если вы закроете дескриптор файла, и программа откроет что-то еще, этот оригинальный дескриптор файла, который вы закрыли, может быть повторно использован для этого «чего-то еще». А теперь угадайте, что произойдет, если программа продолжит работу, думая, что она работает с файлом (чей дескриптор вы закрыли), когда фактически этот дескриптор файла теперь указывает на что-то другое.
см. сообщение Раймонда Чена на эту тему
Предположим, у службы поиска есть файл, открытый для индексации, но он временно застрял, и вы хотите удалить файл, поэтому вы (неразумно) принудительно закрываете дескриптор. Служба индекса поиска открывает свой файл журнала, чтобы записать некоторую информацию, и дескриптор удаленного файла повторно используется в качестве дескриптора файла журнала. Завершенная операция, наконец, завершается, и служба индекса поиска, наконец, подходит к закрытию того дескриптора, который у нее был открыт, но в конечном итоге невольно закрывает дескриптор файла журнала.
Служба индекса поиска открывает другой файл, скажем, файл конфигурации для записи, чтобы обновить некоторое постоянное состояние. Дескриптор файла журнала перерабатывается как дескриптор файла конфигурации. Служба индекса поиска хочет записать некоторую информацию, поэтому она записывает в свой файл журнала. К сожалению, дескриптор файла журнала был закрыт, и этот дескриптор повторно использовался для его файла конфигурации. Зарегистрированная информация попадает в файл конфигурации, повреждая его.
Между тем, другой дескриптор, который вы принудительно закрыли, был повторно использован как дескриптор мьютекса, который используется для предотвращения повреждения данных. Когда оригинальный дескриптор файла закрыт, дескриптор мьютекса закрывается и защита от повреждения данных теряется. Чем дольше служба работает, тем более поврежденными становятся ее индексы. В конце концов, кто-то замечает, что индекс возвращает неверные результаты. И когда вы пытаетесь перезапустить службу, она терпит неудачу, потому что ее файлы конфигурации были повреждены.
Вы сообщаете о проблеме компании, которая предоставляет службу индекса поиска, и они определяют, что индекс был поврежден, файл журнала загадочным образом прекратил запись, а файл конфигурации был перезаписан мусором. Некоторому плохому специалисту поручена безнадежная задача выяснить, почему служба портит свои индексы и файлы конфигурации, не зная, что источником повреждения является то, что вы принудительно закрыли дескриптор.
How To Know Which Process is Using a File or Folder in Windows
Ever wondered which program has a particular file or directory open? Quite often, when trying to delete a folder, Windows reports this:
This error also happens with a file, when we tried to move a file, or delete those file. How we can find out which program or application is currently using it and preventing us to delete/move it? To get the process holding those folder or file, we can use these two utilities:
Resource Monitor
For Windows 7 and above, you can use the built-in Resource Monitor.
Open Resource Monitor, which can be found
- By searching for resmon.exe in the start menu, or
- As a button on the Performance tab in your Task Manager
Resource Monitor from Task Manager’s Performance Tab
From CPU tab, use the search field in the Associated Handles section
When you’ve found the handle, you can identify the process by looking at the Image and/or PID column. You can then close the application if you are able to do that, or just right-click the row and you’ll get the option of killing the process (End Process) right there.
Process Explorer
Process Explorer shows you information about which handles and DLLs processes have opened or loaded.
- Open Process Explorer (running as «administrator») by running procexp.exe or procexp64.exe.
- Enter the keyboard shortcut Ctrl+F. Alternatively, click the “Find” menu and select “Find a Handle or DLL”.
Process Explorer — Find Handle or DLL
- Type in the name of the locked file or other file of interest in the Search dialog box, then click «Search». Partial names are usually sufficient.
- A list will be generated. There may be a number of entries. Click one of the entry, it’ll «Refreshing handles».
Process Explorer — Search
Same as Resource Monitor, an individual handle in the list can be killed by selecting it and pressing the delete key (or Close Handle). However, please be careful when deleting handles, as system instabilities may occur. Rebooting your system maybe will free the locked file/folder.
Process Explorer — Close Handle
Handle is a command line version of Process Explorer.
My Take
I prefer to use Resource Monitor compare to Process Explorer since Process Explorer is slower (especially during «Refreshing handles» process). If I can’t find the handle in Resource Monitor, then I use Process Explorer.
Liked this Tutorial? Share it on Social media!
Gizmo’s Freeware
Login / Register
Main menu
How to Find Out Which Windows Process is Using a File
Last updated by v.laurie on 03. February 2021 — 14:53
Ever try to delete, move, or rename a file only to get a Windows system warning with something like one of these messages?
- «Cannot delete file: Access is denied»
- «There has been a sharing violation»
- «The source or destination file may be in use»
- «The file is in use by another program or user».
- «Make sure the disk is not full or write-protected and that the file is not currently in use»
One of the best ways to handle locked files or folders is to use the free Microsoft program Process Explorer. The program has been described in another article and here is how to use it to find out what program, DLL, or handle is using a file or folder. You will need to run as administrator.
How to find out what program is using a file
In Windows 7 or 8, the system message may tell you what program is using the file. If it doesn’t or if you are using Windows XP, there is a simple way to find the program:
- Open Process Explorer, running as administrator.
- On the toolbar, find the gunsight icon on the right (shown highlighted in the figure shown below).
- Drag the icon and drop it on the open file or folder that is locked.
- The executable that is using the file will be highlighted in the Process Explorer main display list.
How to find out which handle or DLL is using a file
- Open Process Explorer, running as administrator.
- Enter the keyboard shortcut Ctrl+F. Altenatively, click the “Find” menu and select “Find a Handle or DLL”.
- A search dialog box will open.
- Type in the name of the locked file or other file of interest. Partial names are usually sufficient.
- Click the button “Search”,
- A list will be generated. There may be a number of entries.
- An individual handle in the list can be killed by selecting it and pressing the delete key. However, care is necessary when deleting handles, as instabilities may occur. Often, just rebooting will free a locked file.
Process Explorer can be downloaded here.
Get your own favorite tip published! Know a neat tech tip or trick? Then why not have it published here and receive full credit? Click here to tell us your tip.
This tips section is maintained by Vic Laurie. Vic runs several websites with Windows how-to’s, guides, and tutorials, including a site for learning about Windows and the Internet and another with Windows 7 tips.
Click here for more items like this. Better still, get Tech Tips delivered via your RSS feeder or alternatively, have the RSS feed sent as email direct to your in-box.
How do you find what process is holding a file open in Windows?
One thing that annoys me no end about Windows is the old sharing violation error. Often you can’t identify what’s holding it open. Usually it’s just an editor or explorer just pointing to a relevant directory but sometimes I’ve had to resort to rebooting my machine.
Any suggestions on how to find the culprit?
16 Answers 16
I’ve had success with Sysinternals Process Explorer. With this, you can search to find what process(es) have a file open, and you can use it to close the handle(s) if you want. Of course, it is safer to close the whole process. Exercise caution and judgement.
To find a specific file, use the menu option Find->Find Handle or DLL. Type in part of the path to the file. The list of processes will appear below.
If you prefer command line, Sysinternals suite includes command line tool Handle, that lists open handles.
Examples
- c:\Program Files\SysinternalsSuite>handle.exe |findstr /i «e:\» (finds all files opened from drive e:\ «
- c:\Program Files\SysinternalsSuite>handle.exe |findstr /i «file-or-path-in-question»
You can use the Resource Monitor for this which comes built-in with Windows 7, 8, and 10.
- Open Resource Monitor, which can be found
- By searching for Resource Monitor or resmon.exe in the start menu, or
- As a button on the Performance tab in your Task Manager
- Go to the CPU tab
- Use the search field in the Associated Handles section
- See blue arrow in screen shot below
When you’ve found the handle, you can identify the process by looking at the Image and/or PID column.
You can then try to close the application as you normally would, or, if that’s not possible, just right-click the handle and kill the process directly from there. Easy peasy!
Just be very careful with closing handles; it’s even more dangerous than you’d think, because of handle recycling — if you close the file handle, and the program opens something else, that original file handle you closed may be reused for that «something else.» And now guess what happens if the program continues, thinking it is working on the file (whose handle you closed), when in fact that file handle is now pointing to something else.
Suppose a search index service has a file open for indexing but has gotten stuck temporarily and you want to delete the file, so you (unwisely) force the handle closed. The search index service opens its log file in order to record some information, and the handle to the deleted file is recycled as the handle to the log file. The stuck operation finally completes, and the search index service finally gets around to closing that handle it had open, but it ends up unwittingly closing the log file handle.
The search index service opens another file, say a configuration file for writing so it can update some persistent state. The handle for the log file gets recycled as the handle for the configuration file. The search index service wants to log some information, so it writes to its log file. Unfortunately, the log file handle was closed and the handle reused for its configuration file. The logged information goes into the configuration file, corrupting it.
Meanwhile, another handle you forced closed was reused as a mutex handle, which is used to help prevent data from being corrupted. When the original file handle is closed, the mutex handle is closed and the protections against data corruption are lost. The longer the service runs, the more corrupted its indexes become. Eventually, somebody notices the index is returning incorrect results. And when you try to restart the service, it fails because its configuration files have been corrupted.
You report the problem to the company that makes the search index service and they determine that the index has been corrupted, the log file has mysteriously stopped logging, and the configuration file was overwritten with garbage. Some poor technician is assigned the hopeless task of figuring out why the service corrupts its indexes and configuration files, unaware that the source of the corruption is that you forced a handle closed.