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

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

问题描述

Linux 平台上进程(C++ 应用程序)检查其实例未运行的最佳方法是什么?

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

推荐答案

执行此操作的标准方法是在某处创建一个 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天全站免登陆