Skip to content

Commit

Permalink
Refactor file locking mechanism
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
qianlifeng committed Apr 28, 2024
1 parent 896212e commit fece4fc
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 15 deletions.
7 changes: 1 addition & 6 deletions Wox/util/single_instance/single_instance_posix.go
Expand Up @@ -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
}

Expand Down
16 changes: 7 additions & 9 deletions Wox/util/single_instance/single_instance_windows.go
Expand Up @@ -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
}

Expand Down

0 comments on commit fece4fc

Please sign in to comment.