toolbox/flock/flock.go

32 lines
646 B
Go

// The flock package provides a file-system mediated locking mechanism on linux
// using the `flock` system call.
package flock
import (
"os"
"syscall"
)
// Lock gets an exclusive lock on the file at the given path. If the file
// doesn't exist, it's created.
func Lock(path string) (*os.File, error) {
perm := os.O_CREATE | os.O_RDWR
fh, err := os.OpenFile(path, perm, 0600)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(fh.Fd()), syscall.LOCK_EX); err != nil {
return nil, err
}
return fh, nil
}
// Unlock releases the lock acquired via the Lock function.
func Unlock(f *os.File) error {
return f.Close()
}