Windows system locked file

Файл заблокирован процессом Windows, как снять блокировку?

Иногда при попытке удалить, переименовать или переместить какой-то файл в Windows вы можете получить сообщение, что файл занят/заблокирован/используется) другим процессом. Чаще всего имя программы, которая держит файл открытым указывается прямо в окне сообщения File Explorer. Чтобы снять блокировку файла достаточно просто закрыть эту программу. Но бывает ситуации, когда какой-то файл и библиотека используется неизвестным или системным процессом. В этом случае снять блокировку с файла немного сложнее.

Сообщение о блокировке файла может выглядеть по-разному. Например в следующем примере указан тип файла и с каким приложением он ассоциирован:

В этом случае вы можете легко понять какое приложение заблокировало файл и закрыть его.

Однако иногда можно увидеть более интересное сообщение, о том, что файл заблокирован неизвестным или системным процессом Windows. Это может быть, как процесс самой ОС Windows, так и другие процессе, работающий с правами System, например, антивирус, агент резервного копирования, база данных mssql и т.д.):

Попробуем разобраться, как понять какой программой, службой или системным процессом Windows занят файл, как разблокировать файл и можно ли разблокировать файл не закрывая родительский процесс.

Самый простой вариант разблокировать файл – завершить процесс, которые его заблокировал. Но это не всегда возможно, особенно на серверах.

Кроме того, это сторонняя утилита, при установке которой нужно быть внимательным, т.к. в процессе она предлагает установить пачку ненужные программы в нагрузку.

Когда процесс в Windows открывает файл, этому потоку ввода/вывода назначается файловый дескриптор (handler). Процесс и его дочерние процессы получают доступ к файлу по этому дескриптору. Через Window API вы можете послать сигнал файловой системе на освобождение данного дескриптора и снятие блокировки с файла.

Как разблокировать файл с помощью Process Explorer?

ProcessExplorer это бесплатная утилита из набора системных утилит Sysinternals, которую можно скачать на сайте Microsoft (https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer). Попробуем с помощью Process Explorer найти, какой процесс заблокировал определенный файл и освободить этот файл, сбросив файловый дескриптор процесса.

  1. ProcessExplorer не требует установки, просто скачайте распакуйте и запустите с правами администратора procexp.exe ;
  2. Выберите меню Find ->Find Handle or DLL (или нажмите Ctrl-F );
  3. Укажите имя файла, который нужно разблокировать и нажмите Search;
  4. Выберите нужный файл. Процесс, который открыл файлы будет выделен в дереве процессов. Можно завершить этот процесс, щелкнув по нему правой кнопкой и выбрав Kill Process Tree. Но можно попробовать закрыть дескриптор файла, не завершая процесс целиком. Дескриптор файла, который вы искали, автоматически выделяется в нижней панели Process Explorer. Щелкните по дескриптору правой кнопкой и выберите Close handle. Подтвердите закрытие файла.

Итак, вы закрыли дескриптор файла, не завершая родительский процесс. Теперь вы можете спокойно удалить или переименовать файл.

Сброс дескриптора файла с помощью утилиты Handle

Handle – это еще одна утилита командной строки из комплекта инструментов Sysinternals (доступна для скачивания на сайте Microsoft (https://docs.microsoft.com/en-us/sysinternals/downloads/handle. Она позволяет найти процесс, который заблокировал ваш файл и снять блокировку, освободив дескриптор.

  1. Скачайте и распакуйте архив с утилитой Handle;
  2. Запустите командную строку с правами администратора и выполните команду: handle64.exe > listproc.txt  Данная команда сохранит список открытых дескрипторов в файл. Можно вывести дескрипторы для каталога, в котором находится файл, который вы хотите изменить: Handle64.exe -a C:\Some\Path или конкретного процесса: handle64.exe -p winword.exe
  3. Откройте файл listproc.txt в любом текстовом редакторе и найдите строку, в которой указано имя заблокированного файла. Скопируйте ID дескриптора файла (значение в hex формате). Затем поднимитесь немного выше к разделу, в котором указан процесс, являющийся владельцем данного дескриптора и запишите его ID. Для процесса запущенного от имени системы скорее всего будет PID 4.

Если система отреагирует на закрытие файла корректно, вы разблокируете ваш файл без необходимости завершать процесс или перезагружать сервер/компьютер.

LockFile function (fileapi.h)

Locks the specified file for exclusive access by the calling process.

To specify additional options, for example creating a shared lock or for block-on-fail operation, use the LockFileEx function.

Syntax

Parameters

A handle to the file. The file handle must have been created with the GENERIC_READ or GENERIC_WRITE access right. For more information, see File Security and Access Rights.

The low-order 32 bits of the starting byte offset in the file where the lock should begin.

The high-order 32 bits of the starting byte offset in the file where the lock should begin.

The low-order 32 bits of the length of the byte range to be locked.

The high-order 32 bits of the length of the byte range to be locked.

Return value

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, the return value is zero (FALSE). To get extended error information, call GetLastError.

Remarks

If the call to LockFile completes synchronously, a completion entry may not be queued when a completion port is associated with the file handle.

The UnlockFile function unlocks a file region locked by LockFile.

Locking a region of a file gives the threads of the locking process exclusive access to the specified region using this file handle. If the file handle is inherited by a process created by the locking process, the child process is not granted access to the locked region. If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region.

Locking a region of a file does not prevent reading from a mapped file view.

You can lock bytes that are beyond the end of the current file. This is useful to coordinate adding records to the end of a file.

Exclusive locks cannot overlap an existing locked region of a file. For more information, see LockFileEx.

If LockFile cannot lock a region of a file, it returns zero immediately. It does not block. To issue a file lock request that will block until the lock is acquired, use LockFileEx without the LOCKFILE_FAIL_IMMEDIATELY flag.

If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the locks are unlocked by the operating system. However, the time it takes for the operating system to unlock these locks depends upon available system resources. Therefore, it is recommended that your process explicitly unlock all files it has locked when it terminates. If this is not done, access to these files may be denied if the operating system has not yet unlocked them.

In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.

Find out which process is locking a file or folder in Windows

How can I find out which process is locking a file or folder in Windows?

For instance, when trying to delete a folder, Windows reports this:

The action can’t be completed because the folder is open in another program

Happens the same with a file, but how do I find out what program or application is currently using it and preventing me from deleting the file or folder?

11 Answers 11

The openfiles command needs to have support for local files enabled, by running openfiles /local on and restarting.

You can use the Resource Monitor for this which comes built-in with Windows 7, 8, and 10.

  1. 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
  2. Go to the CPU tab
  3. 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!

A couple of options:

Microsoft/SysInternals Process Explorer — Go to Find > Find Handle or DLL. In the «Handle or DLL substring:» text box, type the path to the file (e.g. «C:\path\to\file.txt») and click «Search». All processes which have an open handle to that file should be listed.

WhoLockMe — Explorer extension which adds a right-click menu option

N.B. WhoLockMe appears to not work with Win 10 (at least I have been unable to register it with either of the 32- or 64-bit versions of regsvr32.exe).

Have a look at Process Explorer ( procexp.exe ).

From its introduction:

Ever wondered which program has a particular file or directory open? Now you can find out.

To find out what process is using a specific file follow these steps:

Go to Find, Find Handle or DLL.. or simply press Ctrl + F .

Enter the name of the file and press Search.

Process Explorer will list all processes that have a handle to the file open. Click on an entry to focus the process in the main window.

Optionally, you can then even close the handle manually through the lower pane ( Ctrl + L ):

LockHunter can unlock any handlers that may have locked your files or folders. Unlike similar freewares, it supports both 32 and 64-bit Windows.

It is a free tool to delete files blocked by something you do not know. LockHunter is useful for fighting against malware, and other programs that are blocking files without a reason. Unlike other similar tools it deletes files into the recycle bin so you may restore them if deleted by mistake.

  • Shows processes locking a file or folder
  • Allows to unlock, delete, copy or rename a locked file
  • Allows to kill locking process
  • Allows to remove locking processes from hard drive
  • Integrates in to Explorer menu
  • It deletes files into the recycle bin, so you may restore them if deleted by mistake
  • Supports both 32 and 64bit Windows

EMCO UnlockIT can identify the process that has locked the file as well as unlock the file so that you may delete/edit/move it. The program is completely free, though the newer version is a bit slower and more bloated than the original (which had a plain, unskinned GUI, but loaded pretty much instantaneously and without an annoying splash screen). Also, the original version used to pop up automatically whenever the error you mentioned is triggered, allowing you to instantly unlock the file and perform the operation you were attempting.

Still, UnlockIT is an incredibly useful program that provides a basic functionality that is critically missing from Windows. It’s among the standard toolkit of utilities that I install on all Windows computers I work on.

A lot of the programs here are outdated. I finally ended up using nirsoft’s OpenedFilesView which worked really well.

Though the best part is the explorer menu integration, which is easy to enable. As per website

Starting from version 1.10, you can launch OpenedFilesView directly from Windows Explorer, and view only the handles of the file or folder that you want to inspect. In order to enable this feature, check the ‘Enable Explorer Context Menu’ under the Options menu. After you enable this feature, you can right-click on any file or folder on Windows Explorer, and choose the ‘OpenedFilesView’ item from the menu. If you run the OpenedFilesView option for a folder, it’ll display all opened files inside that folder. If you run the OpenedFilesView option for a file, it’ll display all opened handles for that file.

How to unlock a file handle locked by SYSTEM or any other active process in Windows

The scenario we’re about to introduce is an unbeatable classic for anyone working with Windows. You need to move, rename or delete a file and – as soon as you try to do that – you’re greeted by the following popup message:

File in Use. The action can’t be completed because the file is open in another program.

Or maybe this one:

The action cannot be completed because the file is open in SYSTEM.

If you’re an experienced Windows user you most certainly know that, when you see something like this, it usually means that there is a running application which still has that file opened in an exclusive mode – thus locking it from any IO write operations: no rename, no move and certainly no delete. Whenever that’s the case, the fix is right around the corner: you close the offending application – be it MS Word, MS Excel, MS Access, Photoshop and so on – then go back to the file and do whatever you want with it. Problem solved!

What to do when there are no active applications that seems to be locking that file? As soon as you are sure about it you can focus your attention to other Windows processes, such as some active services that could have it open: Antivirus software, Database services, Source Control Managers, Software Optimizers, Backup Tools, Firewall/security systems and so on. Again, if you’re a seasoned Windows user, you will have no problem to figure it out soon enough.

However there is always a small chance that, after you spent a reasonable amount of time checking and/or temporarily shutting down your resident software, you would still have absolutely no idea of what process is actually keeping that file open. Whenever this happens, you’re going to equip yourself with a few freeware tools that might really help you fixing your issue for good.

Solution #1 (bad): Unlocker

If we don’t want to bother about what’s happening to our system and just want to release that damn file we can think about trying to use Unlocker, a freeware application made by Cedrick Collomb that could automatically fix your issue… or not! I personally don’t recommend using this software for at least two reasons:

  1. You won’t learn anything from using that, including what process (or process chain) will be abruptly shutdown with the intent to free your file.
  2. The program is freeware, but it carries a huge amount of bloatware you need to opt-out from: doing that will even require some attention, because the setup program will try to guide you into installing them and I just really don’t like it.

As a viable alternative you could also try IOBit Unlocker, which is basically the IOBit attempt to capitalize the “unlocker” brand because the original author didn’t make it into a commercial hit (yet). The software is also freeware and it gets the job done just like the former one.

Solution #2 (good): Process Explorer

With Sysinternals Process Explorer (or simply ProcessExplorer) things start looking good. This small, yet great portable utility (no setup, just download and run) allows you to see all the currently active processes within your system, including the names of their owning accounts and a full list of handles (files) that the process selected in the top window has opened, including (if we switch it to DLL mode) the system DLLs: this basically means that we can fully understand what’s going on, and which process is holding our files.

The tool also features a powerful search capability that will quickly show you which processes have particular handles opened or DLLs loaded. This will allow us to use it to easily fix most unwanted file locks in a matter of seconds: we just have to search for the locked file, retrieve the process which is keeping the handle and close (or kill) it accordingly.

Solution #3 (great): Handle

SolutionExplorer is a great analysis tool, yet it lacks some useful options to actually fix our specific issue: altough we can use it to kill a whole process, it doesn’t provide a way to release a specific handle: whenever we’re dealing with files locked by processes we cannot kill, such as SYSTEM, this can be a problem. In order to achieve such surgical result we need to get our hands to another great Sysinternals utility that goes by the name of Handle.

Handle is basically the console version of ProcessExplorer: think of it like a ProcessExplorer with command-line options instead of the GUI. This could make it less intuitive when we need to investigate our system, yet it has extremely powerful tools when it comes to fix the issues we found.

The most common usage of Handle – for our specific scenario – is the following:

  • Download Handle and unzip it into a folder of your choice.
  • Open a command prompt window with administrative priviledges and input the following command:
    Handle64.exe > output . txt . The tool will then create a list of active processes/handles and write the (huge) outcome into the output.txt file.
  • Do not close the command prompt, as you will need it again. Open the output.txt file with your favourite text editor and search for a row containing your locked file name. Once you find it, look for the HEX number to the left and write it down: this is the ID of the handle you need to close. Right after that, go up through the file until you reach the parent row, which contains the informations about the process which is holding that handle. Again, look for the small HEX number to the left and write it down: this is the ID of the process you’ll need to use in the following step. As a side note: SYSTEM process ID is usually 4, although it could vary in the future.
  • Go back to the command prompt and try to close the handle by typing the following:
    handle.exe -c handleID > -p processID > , replacing the placeholders with the values you found in the previous step.

If everything goes correctly, you will fix your problem without killing the process and – more importantly – without having to reboot the system.

Читайте также:  Настройка удаленного управления сервером windows 2012
Оцените статью