1

How to check that another instance of program already running under UNIX system? And exit() if so.

I'm already use file with pid on it when the process start. Then I check pid that its exists. BUT time to time program run on unexpected behavior and I have tons of copies of the program running.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
abrahab
  • 2,430
  • 9
  • 39
  • 64
  • 1
    Hard to tell what's actually going wrong, if you prefer to keep your code undisclosed. – πάντα ῥεῖ Jul 30 '14 at 23:19
  • @πάνταῥεῖ seems there are some interval before new pid write to file and before another instance read the file and make decision run or not and write other pid. so, concurrence start. i want to try some other algoritm. – abrahab Jul 30 '14 at 23:37
  • _'unexpected beaver'_ What a cute "blooper" :-D. Something like "Whoops! Unshaved :-/" ... – πάντα ῥεῖ Jul 30 '14 at 23:49
  • There's no need to mention the language in the title; that's what the tag is for. In any case, the name of the language is C++, not cpp; the name "cpp" more commonly refers to the C preprocessor. – Keith Thompson Jul 30 '14 at 23:53
  • possible duplicate of [How to create a single instance application in C](http://stackoverflow.com/questions/5339200/how-to-create-a-single-instance-application-in-c) – Roland Smith Aug 04 '14 at 16:19

2 Answers2

1

Use an appropriate synchronization mechanism (e.g. a process shared semaphore), to prevent starting your program twice.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • description "sounds good" on the linked thread. would not prevent a bit of code with "how to". pity that the author of that thread has not added it already. – abrahab Jul 31 '14 at 00:13
  • @abrahab Yeah, may be not the best link I have chosen first. I've changed it, try [this one](http://stackoverflow.com/questions/6477525/interprocess-mutex-with-pthreads) it fit's better what you need IMHO. – πάντα ῥεῖ Jul 31 '14 at 00:21
  • there is some difference between the previous link and this. mutex vs. semaphores :) on the first link http://stackoverflow.com/questions/1748902/linux-inter-process-reentrant-semaphore – abrahab Jul 31 '14 at 00:33
  • @abrahab _'there is some difference between the previous link ...'_ Yes of course, that's why I've changed it. Hope this one's giving more value for you, to solve your problem. – πάντα ῥεῖ Jul 31 '14 at 00:41
1

If you are writing pids to a file then you should serialise access to the file with flock.