-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
flock_nix.go
49 lines (40 loc) · 1.15 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
//go:build !windows
// +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 isIOS {
// on iOS, our share extension can have multiple copies running, and furthermore this lock
// doesn't do anything there, so let's just do nothing.
f.G().Log.Debug("Skipping PID file lock on iOS")
return nil
}
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)
err = f.file.Sync()
if err != nil {
f.file.Close()
f.file = nil
return PIDFileLockError{f.name}
}
f.G().Log.Debug("Locked pidfile %s for pid=%d", f.name, pid)
return nil
}