Fix bd-54: Prevent multiple daemon instances via file locking
- Implemented daemon.lock using flock (Unix) and LockFileEx (Windows) - Lock acquired before PID file, held for daemon lifetime - Eliminates race conditions in concurrent daemon starts - Backward compatible: falls back to PID check for old daemons - Updated isDaemonRunning() to check lock availability - All tests pass including new lock and backward compatibility tests Amp-Thread-ID: https://ampcode.com/threads/T-0e2627f4-03f9-4024-bb4b-21d23d296300 Co-authored-by: Amp <amp@ampcode.com>
This commit is contained in:
35
cmd/bd/daemon_lock_windows.go
Normal file
35
cmd/bd/daemon_lock_windows.go
Normal file
@@ -0,0 +1,35 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// flockExclusive acquires an exclusive non-blocking lock on the file using LockFileEx
|
||||
func flockExclusive(f *os.File) error {
|
||||
// LOCKFILE_EXCLUSIVE_LOCK (2) | LOCKFILE_FAIL_IMMEDIATELY (1) = 3
|
||||
const flags = windows.LOCKFILE_EXCLUSIVE_LOCK | windows.LOCKFILE_FAIL_IMMEDIATELY
|
||||
|
||||
// Create overlapped structure for the entire file
|
||||
ol := &windows.Overlapped{}
|
||||
|
||||
// Lock entire file (0xFFFFFFFF, 0xFFFFFFFF = maximum range)
|
||||
err := windows.LockFileEx(
|
||||
windows.Handle(f.Fd()),
|
||||
flags,
|
||||
0, // reserved
|
||||
0xFFFFFFFF, // number of bytes to lock (low)
|
||||
0xFFFFFFFF, // number of bytes to lock (high)
|
||||
ol,
|
||||
)
|
||||
|
||||
if err == windows.ERROR_LOCK_VIOLATION || err == syscall.EWOULDBLOCK {
|
||||
return ErrDaemonLocked
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user