Thomas Sampson

Preventing Multiple Process Instances In C++

Leave a comment

Here is a quick C++ class I knocked up earlier this week which can be used to ensure that only a single instance of your application is running at any given time, using a system-wide mutex object along with a unique process identifier to prevent concurrent execution. The implementation provided is Windows only but could easily be adapted for other platforms using pthread_mutex_trylock.

ProcessInstance Class

#include <windows.h>
#include <string>

class ProcessInstance
{
public:
	ProcessInstance(const std::string& processIdentifier)
		: m_bIsAlreadyRunning(false), m_hProcessInstanceLock(0)
	{
		m_hProcessInstanceLock = ::CreateMutex(0, true, processIdentifier.c_str());
		m_bIsAlreadyRunning = (::GetLastError() == ERROR_ALREADY_EXISTS);
	}

	~ProcessInstance()
	{
		if(m_hProcessInstanceLock)
		{
			::ReleaseMutex(m_hProcessInstanceLock);
		}
	}

	bool IsAlreadyRunning() const
	{
		return m_bIsAlreadyRunning;
	}

private:
	bool m_bIsAlreadyRunning;
	HANDLE m_hProcessInstanceLock;
};

Usage

ProcessInstance gProcess("my_process_guid_here");
int main(int argc, char* argv[])
{
	if(gProcess.IsAlreadyRunning())
	{
		return 0;
	}
}
Advertisements

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s