From fece4fced4fb32d366ce140882ee09e41e0ed0fd Mon Sep 17 00:00:00 2001 From: qianlifeng Date: Sun, 28 Apr 2024 20:42:05 +0800 Subject: [PATCH] Refactor file locking mechanism The file locking mechanism in both Windows and POSIX systems has been modified. This update restructures the way files are opened for writing and locked. Unnecessary file existence checks have been eliminated, and a more proficient use of the defer statement for file closing is included. On a failure, the file will still be properly closed. This should considerably enhance the efficiency and reliability of the lock function. --- .../single_instance/single_instance_posix.go | 7 +------ .../single_instance/single_instance_windows.go | 16 +++++++--------- 2 files changed, 8 insertions(+), 15 deletions(-) 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 }