func Lock() {
lockFile := "./lock.pid"
lock, err := os.Open(lockFile)
if err == nil {
defer lock.Close()
filePid, err := ioutil.ReadAll(lock)
if err == nil {
pidStr := fmt.Sprintf("%s", filePid)
pid, _ := strconv.Atoi(pidStr)
_, err := os.FindProcess(pid)
if err == nil {
fmt.Printf("[ERROR] 工具已启动[%s].\n", pidStr)
os.Exit(1)
}
}
}
lock, err = os.Create(lockFile)
if err != nil {
log.Fatal("创建文件锁失败", err)
}
defer lock.Close()
pid := fmt.Sprint(os.Getpid())
lock.WriteString(pid)
}
感谢
Golang 防止多个进程重复执行通过文件锁
Golang如何保证不重复执行同一个进程