How to allow just one instance to be running from c++ application
exe?!
More details:
Platform: windows, but I prefer a cross-platform solution...
If the user ran the exe and there is another instance already running,
the new exe sends message (ex. string) to the running one and
terminate.
Any ideas and/or thoughts will be much appreciated.
There's no standard solution; the usual solution under Unix
(which should also work under Windows) is to atomically create a
file with the process id of the program in a fixed location.
The "atomically" means that you'll have to use some platform
specific requests, not simple ofstream. Under Unix, this is
done by using the modes O_EXCL | O_CREAT in the open request,
under Windows, there is a flag CREATE_NEW for CreateFile which
sounds like it would do the same thing. If the open succeeds,
you're fine. If it fails, and the error is EEXIST (Unix) or
ERROR_FILE_EXISTS (Windows), then either another instance of the
executable is running, or a previous instance didn't terminate
cleanly, and failed to delete the file. (To solve the problem
concerning failing to delete the file: use a small batch script
to start your program, which deletes the file when your program
has finished, regardless of why it finished, and add an
automatic action on booting to delete the file.) Any other
error, of course, is a serious problem, and probably means that
your program wasn't installed correctly.
It's probably possible to use the registry, rather than a file,
under Windows; I'm not familiar with this, however. And under
Unix (and possibly Windows as well), it's possible to obtain a
list of running processes (reading from a pipe from ps under
Unix), and see if your program is there---this solution is
subject to race conditions, however.