kde-lockscreen-suspend-display/lockfile/lockfile.go

50 lines
748 B
Go

package lockfile
import (
"errors"
"os"
"syscall"
)
type Lockfile struct {
path string
fd int
}
func New(path string) *Lockfile {
return &Lockfile{path: path}
}
func (lf *Lockfile) Lock() error {
fd, err := syscall.Open(lf.path, syscall.O_CREAT | syscall.O_RDWR, 0600)
if err != nil {
return err
}
lf.fd = fd
err = syscall.Flock(lf.fd, syscall.LOCK_EX | syscall.LOCK_NB)
if err != nil {
return err
}
return nil
}
func (lf *Lockfile) Unlock() error {
if lf.fd == 0 {
panic(errors.New("Lockfile was not locked"))
}
err := syscall.Flock(lf.fd, syscall.LOCK_UN)
if err != nil {
return err
}
err = syscall.Close(lf.fd)
if err != nil {
return err
}
os.Remove(lf.path)
if err != nil {
return err
}
return nil
}