forked from jun283/go-application-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
55 lines (48 loc) · 976 Bytes
/
utils.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
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"syscall"
)
func Singleton() {
pid := fmt.Sprint(os.Getpid())
wd, _ := os.Getwd()
fp := wd + "/my.pid"
if _, err := os.Stat(fp); os.IsNotExist(err) {
//file is not exist
fmt.Println("Create pid file:", fp, pid)
f, _ := os.Create(fp)
f.WriteString(pid)
f.Close()
return
}
f, err := os.OpenFile(fp, os.O_RDWR, 0666)
if err != nil {
panic(err.Error())
}
defer f.Close()
x, err := ioutil.ReadAll(f)
if err != nil {
panic(err.Error())
}
iPid, _ := strconv.Atoi(fmt.Sprintf("%s", x))
process, err := os.FindProcess(iPid)
if err != nil {
panic(err)
}
err = process.Signal(syscall.Signal(0))
//fmt.Printf("process.Signal on pid %d returned: %v\n", iPid, err)
if err != nil {
f.Close()
os.Remove(fp)
f, _ := os.Create(fp)
f.WriteString(pid)
f.Close()
fmt.Println("process:", pid)
} else {
fmt.Println("Stopped! One instance is working.PID:", iPid)
os.Exit(0)
}
}