Is there a way to check, if a program is itself already running? I have only found answers for MS windows; is there a platform-independent/*nix way to do so?
CodePudding user response:
On POSIX, you can use named semaphores for this purpose.
Whenever the program starts, it should use the function sem_open
to open a semaphore with a unique name that is hard-coded into the program, creating the semaphore if it does not already exist, and then use sem_trywait
to attempt to acquire the semaphore. The initial value of the semaphore should be 1. If acquiring the semaphore fails due to the semaphore already having been acquired, then the program can probably assume that another instance of the same program is already running.