forked from keybase/client
/
flock_nix.go
37 lines (28 loc) · 831 Bytes
/
flock_nix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
// +build !windows
package libkb
import (
"fmt"
"os"
"syscall"
)
// Lock writes the pid to filename after acquiring a lock on the file.
// When the process exits, the lock will be released.
func (f *LockPIDFile) Lock() (err error) {
if f.file, err = os.OpenFile(f.name, os.O_CREATE|os.O_RDWR, 0600); err != nil {
return PIDFileLockError{f.name}
}
// LOCK_EX = exclusive
// LOCK_NB = nonblocking
if err = syscall.Flock(int(f.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
f.file.Close()
f.file = nil
return PIDFileLockError{f.name}
}
pid := os.Getpid()
fmt.Fprintf(f.file, "%d", pid)
f.file.Sync()
G.Log.Debug("Locked pidfile %s for pid=%d", f.name, pid)
return nil
}