Wednesday, August 31, 2022

[SOLVED] C - check if this program is already running

Issue

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?

id='dv3'>

Solution

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.



Answered By - Andreas Wenzel
Answer Checked By - Katrina (WPSolving Volunteer)