Windows file server locked files

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.

How to View and Close Open Files in Windows Server SMB Share?

Windows file server administrators often have to force close the shared files that are open simultaneously by multiple users. This usually happens if the desktop software doesn’t work as expected, the user logs off incorrectly, or when the user opened a file and forgot to close it (went home, on vacation, etc.). In all these cases, the file on the shared network folder is still open (and locked) and cannot be modified by other users. Other users can see such a message when trying to open a locked file (depending on the application used): The document filename is locked for editing by another user. To open a read-only copy of his document, click…

Читайте также:  Lenovo b560 драйвера видеокарты windows 10 64

In this article we’ll show you how to get the list of open files on a Windows file server, find out which user locked a file on a shared folder, and how to close (reset) file sessions to unlock open files.

View Open Files on a Shared Network Folder on Windows Server

You can get the list of files opened by users on Windows file server using the built-in Computer Management ( compmgmt.msc ) graphic snap-in.

Open the Computer Management console on your file server (or connect to the server remotely from the management console running on your computer) and go to System Tools -> Shared Folders -> Open files. A list of open files on current SMB server is displayed on the right side of the window. The list contains the local path to the file, the name of the user account that opens the file, the number of locks and the mode in which the file is opened (Read or Write+Read).

You can get the same list of open files using the built-in openfiles.exe console tool. For example, using the following command you can get the Session ID, username and full local path to the open file:

openfiles /Query /fo csv |more

You can display a list of open files on a remote server. For example, you need to list all open files in shared folders on the lon-fs01 host:

openfiles /Query /s lon-fs01 /fo csv

How to Find Out Who is Locking a File in a Shared Folder?

To identify the user who opened (locked) the filename.docx file on the shared network folder on the remote server lon-fs01, run this command:

openfiles /Query /s lon-fs01 /fo csv | find /i «filename.docx»

You can specify only a part of the file name. For example, you need to find out who opened an XLSX file containing “sale_report” in its name. Use the following pipe:

openfiles /Query /s lon-fs01 /fo csv | find /i «sale_report»| find /i «xlsx»

Of course you can find this file in the Computer Management GUI, but it’s less convenient (this console doesn’t provide search feature).

How to Forcibly Close an Open File on a SMB Share?

To close an open file, find it in the list of files in Open File section and select Close Open File in the context menu.

If there are hundreds of open files on your file server, it won’t be easy to find the specific file in the console. It is more convenient to use the Openfiles command line tool. As we have already told, it returns the session ID of the open file. Using this session ID you can force close the file by resetting the SMB connection.

First, you need to find the session ID of the open file:

openfiles /Query /s lon-fs01 /fo csv | find /i «farm»| find /i «.xlsx»

Disconnect the user from file using the received SMB session ID:

openfiles /Disconnect /s lon-fs01 /ID 617909089

You can forcefully reset all sessions and unlock all files opened by a specific user:

openfiles /disconnect /s lon-fs01/u corp\mjenny /id *

Get-SMBOpenFile: Find and Close Open File Handlers Using PowerShell

New cmdlets to manage shares and files on an SMB server appeared in PowerShell version for Windows Server 2012/Windows 8. These cmdlets can be used to remotely close network connections to an open file.

You can get a list of open files using the Get-SMBOpenFile cmdlet. Close-SmbOpenFile is used to close/reset the connection to a remote file.

To display a list of open files on the Windows SMB server, run the command:

The command returns the file ID, session ID and full file name(path).
You can display a list of open files with user and computer names (IP addresses):

You can list all files opened by a specific user:

Get-SMBOpenFile –ClientUserName «corp\mjenny»|select ClientComputerName,Path

or from a specific computer/server:

Get-SMBOpenFile –ClientComputerName 192.168.1.190| select ClientUserName,Path

You can display a list of open files by pattern. For example, to list all exe files opened from the shared folder:

Читайте также:  Microsoft sql server express linux

or open files with a specific name:

The Close-SmbOpenFile cmdlet is used to close the open file handler. You can close the file by ID:

Close-SmbOpenFile -FileId 4123426323239

But it is usually more convenient to close the file by name:

Get-SmbOpenFile | where <$_.Path –like "*annual2020.xlsx">| Close-SmbOpenFile -Force

With the Out-GridView cmdlet, you can make a simple GUI form for finding and closing open files. The following script will list open files. You should use the built-in filters in the Out-GridView table to find open files for which you want to reset the SMB sessions. Then you need to select the required files and click OK. As a result, the selected files will be forcibly closed.

Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID| Out-GridView -PassThru –title “Select Open Files”|Close-SmbOpenFile -Confirm:$false -Verbose

How to Close Open Files on Remote Computer Using PowerShell?

The Get-SMBOpenFile and Close-SmbOpenFile cmdlets can be used to remotely find and close open (locked) files. First, you need to connect to a remote Windows SMB server via a CIM session:

$sessn = New-CIMSession –Computername lon-fs01

The following command will find the SMB session for the open file pubs.docx and close the file session.

Get-SMBOpenFile -CIMSession $sessn | where <$_.Path –like "*pubs.docx">| Close-SMBOpenFile -CIMSession $sessn

Confirm closing of the file by pressing Y . As a result, you have unlocked the file. Now other users can open it.

With PowerShell, you can close SMB sessions and unlock all files that a specific user has opened (a user went home and didn’t release the open files). For example, to reset all file sessions of the user mjenny, run this command:

Get-SMBOpenFile -CIMSession $sessn | where <$_.ClientUserName –like "*mjenny*">|Close-SMBOpenFile -CIMSession $sessn

Управление фильтрами блокировки файлов File Screening Management

Область применения: Windows Server 2019, Windows Server 2016, Windows Server (половина ежегодного канала), Windows Server 2012 R2, Windows Server 2012, Windows Server 2008 R2 Applies to: Windows Server 2019, Windows Server 2016, Windows Server (Semi-Annual Channel), Windows Server 2012 R2, Windows Server 2012, Windows Server 2008 R2

На узле Управление фильтрами блокировки файлов оснастки консоли управления Microsoft® (MMC) диспетчера ресурсов файлового сервера можно выполнять следующие задачи: On the File Screening Management node of the File Server Resource Manager MMC snap-in, you can perform the following tasks:

  • Создавать фильтры блокировки файлов, чтобы управлять типами файлов, которые пользователи могут сохранять, а также создавать уведомления, отправляемые при попытке сохранения пользователями запрещенных фалов. Create file screens to control the types of files that users can save, and generate notifications when users attempt to save unauthorized files.
  • Определять шаблоны фильтров блокировки файлов, которые можно применять к новым томам или папкам, а затем использовать во всей организации. Define file screening templates that can be applied to new volumes or folders and that can be used across an organization.
  • Создавать исключения для фильтров блокировки файлов, повышающих гибкость правил фильтров блокировки файлов. Create file screening exceptions that extend the flexibility of the file screening rules.

Например, с их помощью можно выполнять следующее. For example, you can:

  • Убедитесь, что в личных папках на сервере не хранятся музыкальные файлы, тем не менее вы можете разрешить хранение определенных типов файлов мультимедиа, которые поддерживают управление юридическими правами или соответствуют политикам компании. Ensure that no music files are stored on personal folders on a server, yet you could allow storage of specific types of media files that support legal rights management or comply with company policies. При схожем сценарии вам может потребоваться предоставить вице-президенту компании специальные разрешения на хранение файлов любого типа в его личной папке. In the same scenario, you might want to give a vice president in the company special privileges to store any type of files in his personal folder.
  • Реализуйте процедуру фильтрации файлов, в соответствии с которой вы будете получать уведомление по электронной почте в случае размещения исполняемого файла на хранение в общей папке, также содержащее информацию о пользователе, разместившем файл, и сведения о точном расположении файла, чтобы можно было предпринять соответствующие меры предосторожности. Implement a screening process to notify you by e-mail when an executable file is stored on a shared folder, including information about the user who stored the file and the file’s exact location, so that you can take the appropriate precautionary steps.
Читайте также:  Windows 10 есть фризы

Этот раздел содержит следующие подразделы: This section includes the following topics:

Чтобы настроить уведомления по электронной почте и определенные возможности создания отчетов, необходимо сначала настроить общие параметры диспетчера ресурсов файлового сервера. To set e-mail notifications and certain reporting capabilities, you must first configure the general File Server Resource Manager options.

Файл заблокирован процессом 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.

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

Оцените статью