forked from marcsauter/single
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle.go
42 lines (35 loc) · 929 Bytes
/
single.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
// package single provides a mechanism to ensure, that only one instance of a program is running
package single
import (
"errors"
"log"
"os"
)
var (
// ErrAlreadyRunning -- the instance is already running
ErrAlreadyRunning = errors.New("the program is already running")
// Lockfile -- the lock file to check
Lockfile string
)
// Single represents the name and the open file descriptor
type Single struct {
name string
Path string
file *os.File
}
// New creates a Single instance
func New(name string) *Single {
return &Single{name: name}
}
// Lock tries to obtain an exclude lock on a lockfile and exits the program if an error occurs
func (s *Single) Lock() {
if err := s.CheckLock(); err != nil {
log.Fatal(err)
}
}
// Unlock releases the lock, closes and removes the lockfile. All errors will be reported directly.
func (s *Single) Unlock() {
if err := s.TryUnlock(); err != nil {
log.Print(err)
}
}