Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing multiple process instances on Linux

Tags:

c++

linux

process

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

like image 456
jackhab Avatar asked Jun 03 '10 08:06

jackhab


1 Answers

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

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.

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

like image 144
MarkR Avatar answered Oct 06 '22 01:10

MarkR