Golang 防止多个进程重复执行通过文件锁
1. 创建锁文件
func lock() { lockFile := "./lock.pid" lock, err := os.Open(lockFile) defer lock.Close() if err == nil { 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].", 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) }
2. 监听端口