HRESULT _Must_inspect_result_ _Success_(SUCCEEDED(return)) LockFileRegions(
_In_ PFILE_INFO pFileInfo,
_Inout_ PLOCK_FILE_INFO pLockInfo
)
;
The LockFileRegions function attempts to lock one or more byte ranges within a file using the
Windows LockFile API. It implements a best-effort, per-region locking strategy
rather than an atomic all-or-nothing model. Each region is locked independently, and partial success is
allowed.
The function receives:
FILE_INFO structure containing a valid file handleLOCK_FILE_INFO structure specifying one or more byte ranges to lock
It then attempts to lock each region individually using LockFile.
If some regions lock successfully but others fail, the function does not roll back the successful locks. This �fail-open� behavior allows callers to:
Successfully locked regions remain locked until explicitly released via
UnLockFileRegions.
pLockInfo must not be NULLpFileInfo must be validnLockRegions must not exceed MAX_LOCK_REGIONSBefore locking begins, the function iterates through all regions:
bLocked, bLockResult, and bUnlockResult to FALSE
For each region, LockFile is called with the region�s offset and length:
bLocked = FALSEbLockResult = FALSEuFailedCountbLocked = TRUEbLockResult = TRUEuLockedCountThe function returns:
S_OK � only if all regions locked successfully
Callers must inspect bLocked for each region to determine which locks succeeded.
UnLockFileRegions is calledLockFile, not LockFileEx)
1. Call LockFileRegions() with 3 regions (A, B, C)
2. Suppose region B fails to lock (maybe it's already locked by another process)
- Region A: bLocked = TRUE (usable)
- Region B: bLocked = FALSE (not locked)
- Region C: bLocked = TRUE (usable)
- Return value: ERROR_LOCK_VIOLATION
3. Caller can immediately use regions A and C for file operations
4. In parallel or later, caller can retry locking region B
5. When done with regions A and C, call UnLockFileRegions() to release them
6. Region B remains unlocked (caller skipped its unlock since bLocked = FALSE)