在Linux上防止多个流程实例 [英] Preventing multiple process instances on Linux

查看:192
本文介绍了在Linux上防止多个流程实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux平台上,进程(C ++应用程序)检查其实例的最佳方法是否已经运行?

What is the best way on Linux platform for the process (C++ application) to check its instance is not already running?

推荐答案

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.

这篇关于在Linux上防止多个流程实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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