在应用程序中检查应用程序实例是否已经在运行的方法有哪些?

huangapple go评论72阅读模式
英文:

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

问题

我有一个按计划运行的应用程序。我希望应用程序能够检查是否已经有一个实例正在运行。如果有一个实例正在运行,则应用程序退出。如果没有运行中的应用程序实例,则继续执行其工作。

我考虑过使用锁或PID文件,并检查文件的存在。我能否使用os.Getpid()或os.Executable()来实现这一目的?

英文:

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?

答案1

得分: 0

我选择了创建一个pid文件并检查该文件的方法。

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("文件监视器应用程序的一个实例已经在运行。")
        
        os.Exit(0)
    }
}
defer pidfile.Close()
英文:

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

huangapple
  • 本文由 发表于 2022年2月1日 12:17:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/70935514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定