Skip to content

Commit b829625

Browse files
authored
feat: Implement mutex for single instance execution (#15)
Introduce a mutex to ensure that only one instance of the application runs at a time, preventing multiple executions.
1 parent d74d7ef commit b829625

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

main.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ package main
33
import (
44
_ "embed"
55
"encoding/json"
6+
"fmt"
67
"os"
78

9+
"golang.org/x/sys/windows"
10+
811
"github.com/getlantern/systray"
912
)
1013

@@ -24,8 +27,24 @@ var config Config
2427
var tailscalePath string
2528
var currentVersion = "v2.1.2"
2629
var startupDir = os.Getenv("APPDATA") + `\Microsoft\Windows\Start Menu\Programs\Startup`
30+
var mutexHandle windows.Handle
2731

2832
func main() {
33+
mutexName, _ := windows.UTF16PtrFromString("Global\\AutoExitNodeMutex")
34+
handle, err := windows.CreateMutex(nil, false, mutexName)
35+
if err != nil {
36+
fmt.Println("Failed to create mutex:", err)
37+
os.Exit(1)
38+
}
39+
mutexHandle = handle
40+
lastErr := windows.GetLastError()
41+
if lastErr == windows.ERROR_ALREADY_EXISTS {
42+
fmt.Println("Only one instance is allowed.")
43+
os.Exit(0)
44+
}
45+
defer windows.ReleaseMutex(mutexHandle)
46+
defer windows.CloseHandle(mutexHandle)
47+
2948
loadConfig()
3049
tailscaleAvailable = isValidTailscalePath(tailscalePath)
3150
systray.Run(autoExitNote, nil)

0 commit comments

Comments
 (0)