您可以使用文件和文件锁来实现此目的,但是,请注意它并不完美,并且不要复制臭名昭着的Firefox错误,即使它尚未运行,它有时会拒绝启动.
它的基本逻辑是:
Invariant:
File xxxxx will exist if and only if the program is running, and the
contents of the file will contain the PID of that program.
On startup:
If file xxxxx exists:
If there is a process with the PID contained in the file:
Assume there is some instance of the program, and exit
Else:
Assume that the program terminated abnormally, and
overwrite file xxxx with the PID of this program
Else:
Create file xxxx, and save the current PID to that file.
On termination (typically registered via atexit):
Delete file xxxxx
Run Code Online (Sandbox Code Playgroud)
除了上面的逻辑之外,您还应该使用锁定的第二个文件来同步对PID文件的访问(即充当互斥锁以使其在进程级并发方面安全).
执行此操作的标准方法是在某处创建一个pidfile,通常包含程序的pid.
你不需要把pid放在那里,你可以放一个独家锁.如果你打开它进行读/写,并用LOCK_EX |来填充它 LOCK_NB,如果文件已被锁定,它将失败.这是无竞争条件的,如果程序崩溃,锁将自动释放.
通常,您希望按用户执行此操作,因此用户的主目录是放置文件的好地方.
如果它是一个守护进程,那么像/ var/run这样的地方会更好.