spawnlock_other.go

 1//go:build !windows
 2
 3package cmd
 4
 5import (
 6	"fmt"
 7	"os"
 8
 9	"golang.org/x/sys/unix"
10)
11
12// acquireSpawnLock takes an exclusive flock on the given file (creating
13// it if necessary) and returns a release function that unlocks and
14// closes the file. Blocks until the lock is acquired.
15func acquireSpawnLock(path string) (func(), error) {
16	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600)
17	if err != nil {
18		return nil, fmt.Errorf("open spawn lock %q: %v", path, err)
19	}
20	if err := unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
21		_ = f.Close()
22		return nil, fmt.Errorf("flock spawn lock %q: %v", path, err)
23	}
24	return func() {
25		_ = unix.Flock(int(f.Fd()), unix.LOCK_UN)
26		_ = f.Close()
27	}, nil
28}