- LockFile function (fileapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- How to View and Close Open Files in Windows Server SMB Share?
- View Open Files on a Shared Network Folder on Windows Server
- How to Find Out Who is Locking a File in a Shared Folder?
- How to Forcibly Close an Open File on a SMB Share?
- Get-SMBOpenFile: Find and Close Open File Handlers Using PowerShell
- How to Close Open Files on Remote Computer Using PowerShell?
- Understanding (the Lack of) Distributed File Locking in DFSR
- Some Background
- Third-Party Solutions
- Deeper Thoughts
- More inforamtion
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…
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:
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
Understanding (the Lack of) Distributed File Locking in DFSR
This article discusses the absence of a multi-host distributed file locking mechanism within Windows, and specifically within folders replicated by DFSR.
Some Background
- Distributed File Locking – this refers to the concept of having multiple copies of a file on several computers and when one file is opened for writing, all other copies are locked. This prevents a file from being modified on multiple servers at the same time by several users.
- Distributed File System Replication – DFSR operates in a multi-master, state-based design. In state-based replication, each server in the multi-master system applies updates to its replica as they arrive, without exchanging log files (it instead uses version vectors to maintain “up-to-dateness” information). No one server is ever arbitrarily authoritative after initial sync, so it is highly available and very flexible on various network topologies.
- Server Message Block — SMB is the common protocol used in Windows for accessing files over the network. In simplified terms, it’s a client-server protocol that makes use of a redirector to have remote file systems appear to be local file systems. It is not specific to Windows and is quite common – a well known non-Microsoft example is Samba, which allows Linux, Mac, and other operating systems to act as SMB clients/servers and participate in Windows networks.
It’s important to make a clear delineation of where DFSR and SMB live in your replicated data environment. SMB allows users to access their files, and it has no awareness of DFSR. Likewise, DFSR (using the RPC protocol) keeps files in sync between servers and has no awareness of SMB. Don’t confuse distributed locking as defined in this post and Opportunistic Locking.
So here’s where things can go pear-shaped, as the Brits say.
Since users can modify data on multiple servers, and since each Windows server only knows about a file lock on itself, and since DFSR doesn’t know anything about those locks on other servers, it becomes possible for users to overwrite each other’s changes. DFSR uses a “last writer wins” conflict algorithm, so someone has to lose and the person to save last gets to keep their changes. The losing file copy is chucked into the ConflictAndDeleted folder.
Now, this is far less common than people like to believe. Typically, true shared files are modified in a local environment; in the branch office or in the same row of cubicles. They are usually worked on by people on the same team, so people are generally aware of colleagues modifying data. And since they are usually in the same site, the odds are much higher that all the users working on a shared doc will be using the same server. Windows SMB handles the situation here. When a user has a file locked for modification and his coworker tries to edit it, the other user will get an error like:
And if the application opening the file is really clever, like Word 2007, it might give you:
DFSR does have a mechanism for locked files, but it is only within the server’s own context. DFSR will not replicate a file in or out if its local copy has an exclusive lock. But this doesn’t prevent anyone on another server from modifying the file.
Back on topic, the issue of shared data being modified geographically does exist, and for some folks it’s pretty gnarly. We’re occasionally asked why DFSR doesn’t handle this locking and take of everything with a wave of the magic wand. It turns out this is an interesting and difficult scenario to solve for a multi-master replication system. Let’s explore.
Third-Party Solutions
There are some vendor solutions that take on this problem, which they typically tackle through one or more of the following methods*:
- Use of a broker mechanism
Having a central вЂtraffic cop’ allows one server to be aware of all the other servers and which files they have locked by users. Unfortunately this also means that there is often a single point of failure in the distributed locking system.
- Requirement for a fully routed network
Since a central broker must be able to talk to all servers participating in file replication, this removes the ability to handle complex network topologies. Ring topologies and multi hub-and-spoke topologies are not usually possible. In a non-fully routed network, some servers may not be able to directly contact each other or a broker, and can only talk to a partner who himself can talk to another server – and so on. This is fine in a multi-master environment, but not with a brokering mechanism.
- Are limited to a pair of servers
Some solutions limit the topology to a pair of servers in order to simplify their distributed locking mechanism. For larger environments this is may not be feasible.
- Make use of agents on clients and servers
- Do not use multi-master replication
- Do not make use of MS clustering
- Make use of specialty appliances
* Note that I say typically! Please do not post death threats because you have a solution that does/does notВ implement one or more of those methods!
Deeper Thoughts
As you think further about this issue, some fundamental issues start to crop up. For example, if we have four servers with data that can be modified by users in four sites, and the WAN connection to one of them goes offline, what do we do? The users can still access their individual servers – but should we let them? We don’t want them to make changes that conflict, but we definitely want them to keep working and making our company money. If we arbitrarily block changes at that point, no users can work even though there may not actually be any conflicts happening! There’s no way to tell the other servers that the file is in use and you’re back at square one.
Then there’s SMB itself and the error handling of reporting locks. We can’t really change how SMB reports sharing violations as we’d break a ton of applications and clients wouldn’t understand new extended error messages anyways. Applications like Word 2007 do some undercover trickery to figure out who is locking files, but the vast majority of applications don’t know who has a file in use (or even that SMB exists. Really.). So when a user gets the message вЂThis file is in use’ it’s not particularly actionable – should they all call the help desk? Does the help desk have access to all the file servers to see which users are accessing files? Messy.
Since we want multi-master for high availability, a broker system is less desirable; we might need to have something running on all servers that allows them all to communicate even through non-fully routed networks. This will require very complex synchronization techniques. It will add some overhead on the network (although probably not much) and it will need to be lightning fast to make sure that we are not holding up the user in their work; it needs to outrun file replication itself — in fact, it might need to actually be tied to replication somehow. It will also have to account for server outages that are network related and not server crashes, somehow.
And then we’re back to special client software for this scenario that better understands the locks and can give the user some useful info (“Go call Susie in accounting and tell her to release that doc”, “Sorry, the file locking topology is broken and your administrator is preventing you from opening this file until it’s fixed”, etc). Getting this to play nicely with the millions of applications running in Windows will definitely be interesting. There are plenty of OS’s that would not be supported or get the software – Windows 2000 is out of mainstream support and XP soon will be. Linux and Mac clients wouldn’t have this software until they felt it wasВ important, so the customer would have to hope their vendors made something analogous.
More inforamtion
Right now the easiest way to control this situation in DFSR is to use DFS Namespaces to guide users to predictable locations, with a consistent namespace. By correctly configuring your DFSN site topology and server links, you force users to all share the same local server and only allow them to access remote computers when their вЂmain’ server is down. For most environments, this works quite well. Alternative to DFSR, SharePoint is an option because of its check-out/check-in system. BranchCache (coming in Windows Server 2008 R2 and Windows 7) may be an option for you as it is designed for easing the reading of files in a branch scenario, but in the end the authoritative data will still live on one server only – more on this here. And again, those vendors have their solutions.