This repository has been archived by the owner on Dec 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwithoutFlock.go
59 lines (48 loc) · 1.62 KB
/
withoutFlock.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
50
51
52
53
54
55
56
57
58
59
// +build !darwin,!freebsd,!linux
package filelock
import (
"fmt"
"os"
"strconv"
)
func (lockHandle *LockHandle) lock() error {
err := os.Remove(lockHandle.filename)
if err != nil && len(err.Error()) > 79 &&
err.Error()[len(err.Error())-79:] == "The process cannot access the file because it is being used by another process." {
return ErrFileIsBeingUsed
}
if err != nil && len(err.Error()) > 42 &&
err.Error()[len(err.Error())-42:] != "The system cannot find the file specified." {
return fmt.Errorf("Remove error: %v", err)
}
lockHandle.file, err = os.OpenFile(lockHandle.filename, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
if err != nil && len(err.Error()) > 79 &&
err.Error()[len(err.Error())-79:] == "The process cannot access the file because it is being used by another process." {
return ErrFileIsBeingUsed
}
if err != nil {
return fmt.Errorf("OpenFile error: %v", err)
}
_, err = lockHandle.file.WriteString(strconv.FormatInt(int64(os.Getpid()), 10))
if err != nil {
return fmt.Errorf("WriteString error: %v", err)
}
return nil
}
func (lockHandle *LockHandle) unlock() error {
err := lockHandle.file.Close()
lockHandle.file = nil
if err != nil {
return fmt.Errorf("Close error: %v", err)
}
err = os.Remove(lockHandle.filename)
if err != nil && len(err.Error()) > 79 &&
err.Error()[len(err.Error())-79:] == "The process cannot access the file because it is being used by another process." {
return nil
}
if err != nil && len(err.Error()) > 42 &&
err.Error()[len(err.Error())-42:] != "The system cannot find the file specified." {
return fmt.Errorf("Remove error: %v", err)
}
return nil
}