且构网

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

在Linux上防止多个流程实例

更新时间:2023-12-02 10:30:28

p>这样做的标准方法是在某处创建一个pidfile,通常包含程序的pid。

The standard way to do this is to create a pidfile somewhere, typically containing the pid of your program.

你不需要把pid放在那里,你可以放一个排它锁。如果你打开它读/写和使用LOCK_EX | LOCK_NB,如果文件已经锁定,它将失败。这是无竞争条件的,如果程序崩溃,锁将自动释放。

You don't need to put the pid in there, you could just put an exclusive lock on it. If you open it for reading/writing and flock it with LOCK_EX | LOCK_NB, it will fail if the file is already locked. This is race-condition free, and the lock will be automatically released if the program crashes.

通常你想要每用户做一次,所以用户的家目录是放置文件的好地方。

Normally you'd want to do it per-user, so the user's home directory is a good place to put the file.

如果它是一个守护进程,像/ var / run之类的更好。

If it's a daemon, somewhere like /var/run is better.