Golang prevent multiple processes Repeat

Create a lock file

lockFile := "./lock.pid"
lock, err := os.Create(lockFile)
if err != nil {
    log.Fatal("创建文件锁失败", err)
}
defer os.Remove(lockFile)
defer lock.Close()

lockFileCustom variable values; lock file needs to be removed after completion of the main function performing read and close the file.

Lock file

err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if err != nil {
    log.Println("上一个任务未执行完成,暂停执行")
    os.Exit(1)
}

syscall.LOCK_EXExclusive lock does not allow other people to read and write. syscall.LOCK_NBCan not block the operation means that the file can not be locked, immediately returned to the process. lock.Fd()Returns a file descriptor, a file descriptor is an index value that points to the current process open file table record. Finally unlock the file after finished.

defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)

Guess you like

Origin www.cnblogs.com/enochzzg/p/11418527.html