Take the 2-minute tour ×

How can i restrict my program to run only instance? Currently i'm running my program as daemon(starts and stops automatically), and when user clicks and tries to launch again(which is not a valid usecase), process gets launched in user context and i would like to avoid this for many reasons.

How can i achieve this?

As of now i'm getting list of processes and doing some checks and exiting at the begining itself but this method is not clean, though it solves my problem.

can someone give me a better solution? And i'm using ps to get process list, is there any reliable API to get this done?

share|improve this question
Maybe you could lock some file on the first launch of your process, and on subsequent launches, you refuse to launch if the file is already locked... (see flock(2)) –  Guillaume Sep 6 '12 at 8:14
it might create problem when your daemon crashes? –  rplusg Sep 6 '12 at 8:17
The manpage for fnctl on Mac OS X says "All locks associated with a file for a given process are removed when the process terminates.", so I guess you would be safe in case of a crash, but you should always be careful not to create deadlocks situation. –  Guillaume Sep 6 '12 at 9:02
see the link: [how-to-prevent-a-linux-program-from-running-more-than-once][1] [1]: stackoverflow.com/questions/3706917/… –  infantcoder May 9 '13 at 7:12

1 Answer 1

up vote 2 down vote accepted

Use a named semaphore with count of 1. On startup, check if this semaphore is taken. If it is, quit. Otherwise, take it.

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

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

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 execs.

share|improve this answer

Your Answer


