forked from postfinance/single
-
Notifications
You must be signed in to change notification settings - Fork 0
/
single_unix_test.go
49 lines (36 loc) · 898 Bytes
/
single_unix_test.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
// +build !windows
package single_test
import (
"os"
"syscall"
"testing"
"github.com/postfinance/single"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSingle(t *testing.T) {
s, err := single.New("unittest")
require.NoError(t, err)
require.NotNil(t, s)
t.Logf("Lockfile: %s", s.Lockfile())
err = s.Lock()
assert.NoError(t, err)
assert.EqualError(t, checkLock(s), single.ErrAlreadyRunning.Error())
err = s.Unlock()
assert.NoError(t, err)
}
func checkLock(s *single.Single) error {
f, err := os.OpenFile(s.Lockfile(), os.O_RDONLY, 0600)
if err != nil {
return err
}
// try to obtain an exclusive lock with the PPID
flock := syscall.Flock_t{
Type: syscall.F_WRLCK,
Pid: int32(os.Getppid()),
}
if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &flock); err != nil {
return single.ErrAlreadyRunning
}
return nil
}