31 lines
921 B
Go
31 lines
921 B
Go
//go:build windows
|
|
|
|
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"syscall"
|
|
"unsafe"
|
|
)
|
|
|
|
// LockFileEx's exclusive byte-range lock is released by Windows if either
|
|
// process exits. The shared lock file coordinates SDK and game server saves.
|
|
func lockPersistentFile() (func(), error) {
|
|
file, err := os.OpenFile("persistent.lock", os.O_CREATE|os.O_RDWR, 0600)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
dll := syscall.NewLazyDLL("kernel32.dll")
|
|
lock := dll.NewProc("LockFileEx")
|
|
unlock := dll.NewProc("UnlockFileEx")
|
|
overlapped := new(syscall.Overlapped)
|
|
const lockfileExclusiveLock = 2 // Win32 LOCKFILE_EXCLUSIVE_LOCK.
|
|
ok, _, callErr := lock.Call(file.Fd(), lockfileExclusiveLock, 0, 1, 0, uintptr(unsafe.Pointer(overlapped)))
|
|
if ok == 0 {
|
|
file.Close()
|
|
return nil, fmt.Errorf("lock persistent: %w", callErr)
|
|
}
|
|
return func() { unlock.Call(file.Fd(), 0, 1, 0, uintptr(unsafe.Pointer(overlapped))); file.Close() }, nil
|
|
}
|