确保 Linux 中应用程序的单个实例 [英] Ensure a single instance of an application in Linux

查看:45
本文介绍了确保 Linux 中应用程序的单个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 WxPython 中开发一个 GUI 应用程序,但我不确定如何确保在任何给定时间在机器上只运行我的应用程序的一个副本.由于应用程序的性质,多次运行没有任何意义,并且会很快失败.在 Win32 下,我可以简单地创建一个命名的互斥锁并在启动时检查它.不幸的是,我不知道 Linux 中有任何工具可以做到这一点.

I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this.

我正在寻找可以在应用程序意外崩溃时自动释放的东西.我不想让我的用户因为我崩溃而不得不手动删除锁定文件.

I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.

推荐答案

有几种常用技术,包括使用信号量.我看到最常用的方法是在启动时创建一个pid 锁定文件",其中包含正在运行的进程的 pid.如果程序启动时该文件已经存在,打开它并抓取里面的pid,检查是否有具有该pid的进程正在运行,如果是在/proc/pid 查看它是否是您的程序的一个实例,如果它退出,则用您的 pid 覆盖该文件.pid 文件的常用名称是 application_name.pid.

There are several common techniques including using semaphores. The one I see used most often is to create a "pid lock file" on startup that contains the pid of the running process. If the file already exists when the program starts up, open it up and grab the pid inside, check to see if a process with that pid is running, if it is check the cmdline value in /proc/pid to see if it is an instance of your program, if it is then quit, otherwise overwrite the file with your pid. The usual name for the pid file is application_name.pid.

这篇关于确保 Linux 中应用程序的单个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆