How to block running two instances of the same program?
<p>I need to make sure that user can run only one instance of my program at a time.<br />
Which means, that I have to check programatically, whether the same program is already running, and quit in such case.</p>

<p>The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instance of the program would check for this file and exit if it found it.<br />
The trouble is, that the program must always exit gracefully and be able to delete the file it created, for this to work.
In case of, say, power outage, the lock file remains in place and the program can't be started again.</p>

<p>To solve this, I decided to store the first program's process ID into the lock file and when another instance starts, it checks if the PID from the file is attached to some running process.<br />
If the file doesn't exist, is empty, or the PID doesn't correspond to any existing process, the program continues to run and writes its own PID to the file.</p>

<p>This seems to work quite fine - even after an unexpected shutdown, the chance that the (now obsolete) process ID will be associated with some other program, seems to be quite low.</p>

<p>But it still doesn't feel right (there <em>is</em> a chance of getting locked by some unrelated process) and working with process IDs seems to go beyond the standard C++ and probably isn't very portable either.</p>

<p>So, is there another (more clean and secure) way of doing this? Ideally one that would work with the ISO 98 C++ standard and on Windows and *nix alike.<br />
If it cannot be done platform-independently, Linux/Unix is a priority for me.</p>
