diff --git a/Wox/util/single_instance/single_instance_posix.go b/Wox/util/single_instance/single_instance_posix.go index 26976f9f0..089f8b11b 100644 --- a/Wox/util/single_instance/single_instance_posix.go +++ b/Wox/util/single_instance/single_instance_posix.go @@ -8,28 +8,23 @@ import ( "wox/util" ) -// CreateLockFile tries to create a file with given name and acquire an -// exclusive lock on it. If the file already exists AND is still locked, it will -// fail. func lock(content string) error { filename := util.GetLocation().GetAppLockFilePath() file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0600) if err != nil { return err } + defer file.Close() err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) if err != nil { - file.Close() return err } if err := file.Truncate(0); err != nil { - file.Close() return err } if _, err := file.WriteString(content); err != nil { - file.Close() return err } diff --git a/Wox/util/single_instance/single_instance_windows.go b/Wox/util/single_instance/single_instance_windows.go index 486ef93ad..1c3eb446f 100644 --- a/Wox/util/single_instance/single_instance_windows.go +++ b/Wox/util/single_instance/single_instance_windows.go @@ -4,27 +4,25 @@ package single_instance import ( "os" + "syscall" "wox/util" ) func lock(content string) error { filename := util.GetLocation().GetAppLockFilePath() - if _, err := os.Stat(filename); err == nil { - // If the files exists, we first try to remove it - if err = os.Remove(filename); err != nil { - return err - } - } else if !os.IsNotExist(err) { + file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600) + if err != nil { return err } + defer file.Close() - file, err := os.OpenFile(filename, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + var overlapped syscall.Overlapped + err = syscall.LockFileEx(syscall.Handle(file.Fd()), syscall.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &overlapped) if err != nil { return err } - _, err = file.WriteString(content) - if err != nil { + if _, err := file.WriteString(content); err != nil { return err }