TryLock attempts to acquire an exclusive, non-blocking lock on the given path. Returns the locked file and an unlock function on success. The caller should read/write through the returned file to avoid Windows mandatory lock conflicts. Returns ErrLocked if the file is already locked by another proce
(path string)
| 14 | // read/write through the returned file to avoid Windows mandatory lock conflicts. |
| 15 | // Returns ErrLocked if the file is already locked by another process. |
| 16 | func TryLock(path string) (f *os.File, unlock func(), err error) { |
| 17 | f, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644) |
| 18 | if err != nil { |
| 19 | return nil, nil, err |
| 20 | } |
| 21 | ol := new(windows.Overlapped) |
| 22 | handle := windows.Handle(f.Fd()) |
| 23 | err = windows.LockFileEx( |
| 24 | handle, |
| 25 | windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, |
| 26 | 0, |
| 27 | 1, 0, |
| 28 | ol, |
| 29 | ) |
| 30 | if err != nil { |
| 31 | _ = f.Close() |
| 32 | if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { |
| 33 | return nil, nil, ErrLocked |
| 34 | } |
| 35 | return nil, nil, err |
| 36 | } |
| 37 | return f, func() { |
| 38 | _ = windows.UnlockFileEx(handle, 0, 1, 0, ol) |
| 39 | _ = f.Close() |
| 40 | }, nil |
| 41 | } |