2

Is there any way to stop a double execution of an application in C++ so only one instance of the application is running at once?


Edit: Windows 7

Spamdark
  • 1,341
  • 2
  • 19
  • 38
  • 3
    Welcome to stackoverflow. The answer to your question depends on what system you're using. Please edit your question to tell us what operating system (Windows, Mac OS X, Linux, etc.) you're using, and what version of that OS. – rob mayoff Aug 21 '12 at 02:11

3 Answers3

3

There is no way to do it in the C++ standard. What you need is to use a mechanism provided by the underlying platform. For example, here is how you would do it on Windows.

Here is how you might do it on Mac OS X. As you can see, the approaches can be different and depends on what you want.

It boils down to checking if your application is running and then exiting if it is.

Here are a few more ways to check if your application is running on Windows (the code is in a different language, but the concepts are the same)

Community
  • 1
  • 1
Carl
  • 43,122
  • 10
  • 80
  • 104
1

If you need a cross-platform solution, you can use Boost.Interprocess:

#include <iostream>
#include <boost\interprocess\sync\named_mutex.hpp>

int main(int, char **argv) {
    using namespace boost::interprocess;
    using namespace std;
    static const char *unique_name = "xyzzy";
    try {
        named_mutex justonce(create_only, unique_name);
        cout << "running..." << endl;

        char c;
        cin >> c;

        named_mutex::remove(unique_name);
    } catch (interprocess_exception) {
        cout << "already running..." << endl;
    }
}
Ferruccio
  • 98,941
  • 38
  • 226
  • 299
-1

You can follow the Singelton Class design pattern to solve your problem. At any time it will create a max of one object.