TryLock attempts to acquire an exclusive, non-blocking flock 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 platform differences with mandatory locking on Windows. Returns ErrLocked if the file is already
(path string)
| 14 | // mandatory locking on Windows. |
| 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 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| 22 | _ = f.Close() |
| 23 | if errors.Is(err, syscall.EWOULDBLOCK) { |
| 24 | return nil, nil, ErrLocked |
| 25 | } |
| 26 | return nil, nil, err |
| 27 | } |
| 28 | return f, func() { |
| 29 | _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) |
| 30 | _ = f.Close() |
| 31 | }, nil |
| 32 | } |