2

These questions How to block running two instances of the same program? , How to create a single instance application in C or C++ and Preventing multiple instances of my application address how to prevent opening multiple instances of the same application for a platform specifically (Windows, Linux).

Is there a cross platform way to achieve this?

Community
  • 1
  • 1
Alexandru Irimiea
  • 2,513
  • 4
  • 26
  • 46

2 Answers2

1

Answering my question, as I didn't find someone else addressing this in the other questions.

This can be achieved in a cross platform way using boost/interprocess/sync/named_mutex (I used boost 1.63)

I tested on both Linux and Windows and the implementation prevents opening a second instance of the application.

The problem that I found is that if I kill the process (on both platforms), the mutex is not removed because the destructor ~MyApplication is not called. So only after system restart I will be able to run the application again.

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

class MyApplication
{
public:
    MyApplication() = default;

    ~MyApplication()
    {
        if (mLockedByThisInstance)
        {
            boost::interprocess::named_mutex::remove("myApplicationMutex");
        }
    }

    bool IsAlreadyRunning()
    {
        mLockedByThisInstance = mNamedMutex.try_lock();

        if (!mLockedByThisInstance)
        {
            return true;
        }

        return false;
    }

    int Run(int argc, char *argv[])
    {
        // Application main loop            
        return 0;
    }

private:
    bool mLockedByThisInstance = false;
    boost::interprocess::named_mutex mNamedMutex{ boost::interprocess::open_or_create,
        "myApplicationMutex" };
};

int main(int argc, char *argv[])
{
    MyApplication myApplication;

    if (myApplication.IsAlreadyRunning())
    {
        std::cout << "MyApplication is already running!\n";
        return 1;
    }

    return myApplication.Run(argc, argv);
}
Alexandru Irimiea
  • 2,513
  • 4
  • 26
  • 46
  • "So only after system restart I will be able to run the application again." And I think this should be worth a bug report with boost. – tobsen Feb 28 '18 at 08:55
-1

This is not really a complete answer, but look into something like holding a specific file handle for exclusive access. You can use this like a mutex, but with the added benefit that the OS should "clean up" the handle on process termination automatically.

I cannot speak to if this will work on Linux, but at least on Windows, this should let you achieve the same effect. Hope that helps.

Nick
  • 6,808
  • 1
  • 22
  • 34