Skip to content

Commit 47718d2

Browse files
authored
Prevent multiple instances (#9)
* Prevent multiple instances of Launchy from running * Handle Ctrl+C signal gracefully
1 parent 00de95d commit 47718d2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/main.go

+34
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package main
22

33
import (
4+
"os"
5+
"os/signal"
46
"strings"
7+
"syscall"
58

69
// TODO: fix this dependency. It's a nice log tho
710
log "github.com/sirupsen/logrus"
@@ -253,7 +256,38 @@ func (app *Application) Main() {
253256
gtk.Main()
254257
}
255258

259+
const lockFile = "/tmp/launchy.lock"
260+
261+
func handleInterruptSignal() {
262+
c := make(chan os.Signal, 1)
263+
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
264+
go func() {
265+
<-c
266+
log.Info("Interrupt signal received. Exiting gracefully...")
267+
gtk.MainQuit()
268+
}()
269+
}
270+
256271
func main() {
272+
file, err := os.OpenFile(lockFile, os.O_CREATE|os.O_RDWR, 0644)
273+
if err == nil {
274+
defer os.Remove(lockFile)
275+
defer file.Close()
276+
277+
// Try to lock the file
278+
err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
279+
if err != nil {
280+
log.Info("Another instance of Launchy is already running.")
281+
return
282+
}
283+
defer syscall.Flock(int(file.Fd()), syscall.LOCK_UN)
284+
} else {
285+
log.Warnf("Failed to create/open lock file: %s", err)
286+
return
287+
}
288+
289+
handleInterruptSignal()
290+
257291
app := NewApplication()
258292
app.Main()
259293
}

0 commit comments

Comments
 (0)