MCPcopy
hub / github.com/cli/cli / TryLock

Function TryLock

internal/flock/flock_unix.go:16–32  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

14// mandatory locking on Windows.
15// Returns ErrLocked if the file is already locked by another process.
16func 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}

Callers 3

TestTryLockFunction · 0.92
TestRecordInstallFunction · 0.92
acquireFLockFunction · 0.92

Calls 2

FdMethod · 0.65
CloseMethod · 0.65

Tested by 2

TestTryLockFunction · 0.74
TestRecordInstallFunction · 0.74