4

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?

user1071136
  • 15,636
  • 4
  • 42
  • 61
rplusg
  • 3,418
  • 6
  • 34
  • 49
  • 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 06 '12 at 08:14
  • it might create problem when your daemon crashes? – rplusg Sep 06 '12 at 08: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 06 '12 at 09:02
  • see the link: [how-to-prevent-a-linux-program-from-running-more-than-once][1] [1]: http://stackoverflow.com/questions/3706917/how-to-prevent-a-linux-program-from-running-more-than-once – infantcoder May 09 '13 at 07:12

1 Answers1

4

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

user1071136
  • 15,636
  • 4
  • 42
  • 61