英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论