forked from marcsauter/single
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle_windows.go
47 lines (39 loc) · 1.05 KB
/
single_windows.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
// +build windows
package single
import (
"fmt"
"os"
"path/filepath"
)
// Filename returns an absolute filename, appropriate for the operating system
func (s *Single) Filename() string {
if len(Lockfile) > 0 {
return Lockfile
}
if s.Path != "" {
return filepath.Join(s.Path, fmt.Sprintf("%s.lock", s.name))
}
return filepath.Join(os.TempDir(), fmt.Sprintf("%s.lock", s.name))
}
// CheckLock tries to obtain an exclude lock on a lockfile and returns an error if one occurs
func (s *Single) CheckLock() error {
if err := os.Remove(s.Filename()); err != nil && !os.IsNotExist(err) {
return ErrAlreadyRunning
}
file, err := os.OpenFile(s.Filename(), os.O_EXCL|os.O_CREATE, 0600)
if err != nil {
return err
}
s.file = file
return nil
}
// TryUnlock closes and removes the lockfile
func (s *Single) TryUnlock() error {
if err := s.file.Close(); err != nil {
return fmt.Errorf("failed to close the lock file: %v", err)
}
if err := os.Remove(s.Filename()); err != nil {
return fmt.Errorf("failed to remove the lock file: %v", err)
}
return nil
}