且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确保 Linux 中应用程序的单个实例

更新时间:2023-11-22 21:27:04

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