Daemonize your go programs by locking the process id file. Simply put the following at the top of your main
,
func main() {
defer pid.Start("monokuma").Stop()
// your code...
}
This will create a monokuma.pid
file in /tmp
with the process id (pid) of the go program when loaded by your operating system. When your `main` exits, the file will be cleaned up.
This will prevent any other instances of your program running at the same time (say running a web server or overloading some resources). Say, when I run
λ monokuma
I can find the PID of it with (no line feed at the end),
λ cat /tmp/monokuma.pid
91100⏎
If I try to start the same program, I will be greeted by
λ ./monokuma
2023/05/17 23:03:03 your app with pid 91100 is already running
-> See more in pid
github repository