Ways to check within an application if an instance of the application is already running?

Issue

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?

Solution

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()

Answered By – user982599

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.