I'm trying to prevent a program from opening another instance if it's already open, to do this I create a file with .lock
extension and remove it when exiting the program. However everything except the remove works.
package main
import (
"os"
"os/signal"
"fmt"
)
func main() {
var test string
exitsig := make(chan os.Signal, 1)
signal.Notify(exitsig, os.Interrupt)
var (
lockstate bool = false
)
if _, err := os.Stat("ms.lock"); err == nil {
return
} else if os.IsNotExist(err) {
var file, err = os.Create("ms.lock")
if err != nil {
return
}
file.Close()
lockstate = true
}
go func() {
<- exitsig
fmt.Println("Error removing file")
fmt.Scanf("%s", &test)
if lockstate {
var err = os.Remove("ms.lock")
if err != nil {
fmt.Println("Error removing file")
fmt.Scanf("%s", &test)
}
}
os.Exit(0)
}()
}
I've tried exiting by ctrl+c
, exiting by pressing the close button on the top right corner of the window but it never sends a signal, the os.Interrupt
signal is never caught. What is the reason for this?
Also, I need the signal to be non-platform specific, so it should work on both windows and unix based systems.