Allow only one executable instance of the program

How can I limit my program to running only an instance? I am currently running my program as a daemon (it starts and stops automatically), and when the user clicks and tries to start again (which is not a valid user), the process starts in the user context, and I would like to avoid this for many reasons.

How can i achieve this?

At the moment, I get a list of processes and do some checks and exit at the very beginning, but this method is not clean, although it solves my problem.

can anyone give me a better solution? And I use ps to get a list of processes, is there any reliable API to do this?

+4
source share
1 answer

Use a named semaphore with a score of 1. At startup, check to see if this semaphore is accepted. If so, give it up. Otherwise, take it.

Proof of concept code: (put somewhere near the application entry point)

#include <semaphore.h> ... if (sem_open(<UUID string for my app>, O_CREAT, 600, 1) == SEM_FAILED) { exit(0); } 

From the sem_open documentation ,

The returned semaphore descriptor is available to the calling process until it is closed with sem_close () or until the caller exits or executes the command.

+2
source

Source: https://habr.com/ru/post/1432660/


All Articles