I have an application that runs on a schedule. I want the application to check if an instance of it is already running. If there is an instance running then the application exits. If no instance of the application is running then it continues on performing it's job.
I thought about using a lock or PID file and checking for the existence of the file. Is there something I could do with os.Getpid() or os.Executable() and accomplish this?
CodePudding user response:
I went the route of just creating a pid file and checking for that.
pidfile, err := os.OpenFile(watcherconfig.TeleportFileWatcher.PIDFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
if os.IsExist(err) {
watcherlog.InfoLogger.Println("An instance of the file watcher application is already running.")
os.Exit(0)
}
}
defer pidfile.Close()
CodePudding user response:
You can run your application as a service and check its state, like this.
$ service x11-common start
$ service x11-common status
$ service x11-common stop
