For a variety of reasons it is often desirable to limit the number of running instances of a program to exactly one on a particular computer. There is a lot of folklore around about how to do this, and much of it is wrong. There are a few good methods, and a lot of flawed ones.
I know. I used a flawed one for years. I even put the technique in our book, "Win32 Programming". I feel suitably embarrassed.
This essay examines some of the many solutions, and points out the problems in those that will fail, and the conditions under which they fail.
What is really dangerous is that Microsoft not only does not document the correct method, but offers two code examples of a fatally-flawed solution, which I discuss in detail.
What is a "multiple instance"?
One of the interesting points that was raised by one correspondent, Daniel Lohmann (mailto:(firstname.lastname@example.org) is that the term "multiple instance" was not well-defined in an earlier version of this essay. He points out that "multiple instance" can mean different things in the multiuser environment of NT. He points out that it is possible to use API calls such as
SwitchDesktop, and therefore it is possible to have multiple users and multiple desktop sessions running under different accounts.
Therefore, there are several issues about why one would not want multiple instances of an application. He categorized them as
- Avoiding multiple instances started in the same user session, no matter how many desktops that user session has, but allowing multiple instances to run concurrently for different user sessions.
- Avoiding multiple instances started in the same desktop, but allowing multiple instances to run as long as each one is in a separate desktop.
- Avoiding multiple instances started for the same user account, no matter how many desktops or sessions running under this account exist, but allowing multiple instances to run concurrently for sessions running under a different user account.
- Avoiding multiple instances started on the same machine. This means that no matter how many desktops are used by an arbitrary number of users, there can be at most one instance of the program running.
He observes that many programmers actually mean (a), and sometimes mean (b) or (c). The technique outlined in the earlier version of this essay always interpreted the question as (d). Note that in the case of Win9x/Millenium, only (d) exists, since there is only one user session and one desktop per machine.
Thus, as you read the essay below, be aware that we are answering only (d) using this technique. Afterwards, I will present his proposed solutions for being able to extend this technique to include (a)-(c). He observes that certain "service-oriented" applications that fit into the class of (d) are often better done as System Services. The service may be started on-demand or at system startup, but all users and all desktops share the same common service.
The correct solution: Using a kernel object
The following code is an adaptation of an example posted in the
microsoft.public.mfc newsgroup by David Lowndes. His example had an option that used
FindWindow, which for reasons I explain below will not work reliably. Instead, my version uses what I consider a more reliable technique to locate the window of the other instance. His code also used a shared (inter-process) variable which introduces another problem which I discuss later. However, if you deem the problem unimportant, you may choose to use the simpler version. This solution is the general solution on which the multi-desktop and multi-user solutions are based; the key difference is in how the unique ID is formed, a topic discussed later.
In the example below, you must declare the function
CMyApp::searcher as a
static class member, for example
static BOOL CALLBACK searcher(HWND hWnd, LPARAM lParam);
You have to declare a registered window message, for example,
UWM_ARE_YOU_ME. For the details of this, see my essay on Message Management. In the
CMainFrame class definition, add a handler for this message:
afx_msg LRESULT OnAreYouMe(WPARAM, LPARAM);
and add a
implement it as follows:
LRESULT CMainFrame::OnAreYouMe(WPARAM, LPARAM)
Now you can implement the
searcher method which looks for the target window.
BOOL CALLBACK CMyApp::searcher(HWND hWnd, LPARAM lParam)
LRESULT ok = ::SendMessageTimeout(hWnd,
if(ok == 0)
return TRUE; if(result == UWM_ARE_YOU_ME)
HWND * target = (HWND *)lParam;
*target = hWnd;
return FALSE; }
return TRUE; }
HANDLE hMutexOneInstance = ::<A name=CreateMutex>CreateMutex</A>( NULL, FALSE,
AlreadyRunning = ( ::GetLastError() == ERROR_ALREADY_EXISTS ||
::GetLastError() == ERROR_ACCESS_DENIED);
if ( AlreadyRunning )
HWND hOther = NULL;
if ( hOther != NULL )
::SetForegroundWindow( hOther );
if ( IsIconic( hOther ) )
::ShowWindow( hOther, SW_RESTORE );
return FALSE; }
After you read the section on Race Conditions you may see that this code has a race condition. If the Mutex was created by instance 1, which is still coming up (it hasn't created its main window yet), and instance 2 finds that the Mutex already exists, it tries to find the window for Instance 1. But since Instance 1 is not yet there, this code does not pop up the window for Instance 1. But that's OK. Because Instance 1 has not yet created its window, it will proceed to create its window successfully and pop up just like you'd expect.
The basic problem: Race Conditions
There is, in any system with potential parallel execution threads, or pseudo-parallel execution threads, a phenomenon known as the "race condition". This is a situation in which the correctness of the cooperation between two (or more, generally) processes is determined by the timing relationship of the execution of certain paths in the programs. If program A reaches a certain point of execution before program B has set things up properly, program A could fail.
Many of the "find the other executing program instance" solutions fail because of race conditions. We'll examine these after we look at a way that actually seems to work.
One of the popular pieces of folklore is to that you can use the
FindWindow API call to avoid multiple instances. This API is very dangerous to use. There is an excellent chance that your application will forever hang while executing this call. In any case, even if the conditions that would cause it to hang do not exist, the techniques surrounding its use are so deeply flawed that such a technique cannot possibly work. So it has two failure modes: no instance comes up, or multiple instances come up. Neither of these is terribly satisfactory.
Unfortunately, this folklore is so popular that even Microsoft believes it. In their KB article Q109175, they suggest a download of a program
onetime.exe which is a self-extracting zipfile that contains an example that does precisely this. KB Q141752 and its accompanying
onet32.exe propagate this myth. Trust me. Been there, done that. This does not work. Do not use this technique.
Why doesn't it work? Well, it works if everything is perfect. But when there is a tiny, minor, little thing wrong, it fails catastrophically, at least as far as the end user is concerned. Furthermore, the thing that is "wrong" does not mean there is a malfunction. A completely correctly-functioning program can cause the failure.
FindWindow call is:
HWND CWnd::FindWindow(LPCTSTR classname, LPCTSTR caption)
The classname parameter can either
NULL, which means that all windows classes will match, or a window class name. (The underlying API call can also accept an
HATOM cast to an
LPCTSTR, but it is rare in MFC to have the
HATOM from a
::RegisterWindowClass call). The caption parameter is a string which is compared to the caption of each window that is enumerated. The function returns the
HWND of the first window whose class name matches classname and whose caption matches caption.
Why won't this work?
Well, unless you have registered the window class of your app using
AfxRegisterClass, you don't know the class name. So, you say, "that's OK, I'll just use
NULL, but I know the caption name".
Well, maybe you do. This week. In this country. For this version. Probably. As long as it isn't an MDI app.
Well, for one thing, you don't want to hardwire a constant value for the caption value. This would be a colossally losing idea. Because if you internationalize the application, you will change the caption name. And so you lose.
Aha! You will put the caption name in the resource file. Then you'll use
LoadString to get it. Well, that's fine, but then you have to make sure that the same
LoadString is used to set the caption. OK, maybe this works. For a dialog-based app. But for other apps, the file name of the input file will be incorporated into the caption, and you can't predict what this is, so already
FindWindow is useless.
So you can't use
FindWindow if you are looking for the caption.
But things get worse.
FindWindow really does an
EnumWindows call, and for each top-level window handle found, it performs a
GetWindowText operation. This is done by sending a
WM_GETTEXT message to the window handle. But if the thread that owns the handle is blocked, on a Semaphore, a Mutex, an Event, an I/O operation, or some other manner, the
SendMessage will block until that thread frees up and runs. But this may never happen. So
FindWindow will block forever, and your application will never come up.
When you have to drive out some considerable distance because your best client can't get the app to start on his machine, you want to make sure that (a) this never happens to him again and (b) it certainly will never happen to any of his customers! It took a long time to find this one.
So, you say, that's clearly a losing idea. I'll use the class name. After all, that's what Microsoft does in their examples, and they Must Know What They Are Doing.
The code Microsoft supplies as an example is flawed. But the superficial flaws mask the deep flaws. For example, the class name is given as a string name. What is not readily apparent is that you really, really have to modify this name to be unique. Globally unique. As in, no other implementor anywhere else in the known Universe would ever use the same name.
Now here's a little story, which you should all take to heart: a long time ago, I wrote a Win16 application. It registered a window class "generic" because I cloned it from the Microsoft generic example. The complaint was "your program fails". Guess what? It tried to register the window class "generic", which someone else who had cloned their application from the generic example had also used. Back in those days, window class names were systemwide global names, so it failed to register the class.
Today, you say, those names are not globally unique; it is perfectly valid to have a program A that registers a class "MainWindow" and a program B that registers a class "MainWindow". This is true. But only if neither ever cares about the other. If Program B starts asking what a window's class name is, it can't tell whether the name "MainWindow" is registered by an instance of itself, or by some other program that never heard of it.
So the first thing to do is make sure your class name is unique, because even though the names are not global, you are about to search for that class name, and you can't tell which of the many registered class instances of the same name you are talking to.
OK, so you have read my other essays and know how to do this by using GUIDGEN. This creates a 128-bit number, expressed as a hex character string, which is known to be globally unique. So you just append it to the human-readable class name. Cool. So you know the name is unique, and you're going to search using that class name. Since you're not falling into the
WM_GETTEXT trap, it won't matter if the other task is hung in some way, because after all, it doesn't have to be running for you to get the class information about the window class.
Guess what. You've just fallen into the Race Condition trap.
Here's a skeleton of the code from one of the Microsoft examples. I've included only the Good Parts.
LPCTSTR lpszUniqueClass = _T("MyNewClass");
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
cs.lpszClass = lpszUniqueClass;
if(!FirstInstance()) return FALSE;
memset(&wndcls, 0, sizeof(WNDCLASS));
wndcls.style = ...;
... other wndcls variable inits here, irrelevant for
... this discussion
wndcls.lpszClassName = lpszUniqueClass;
... rest of InitInstance here...
CMainFrame* pMainFrame = new CMainFrame; ... more here
CWnd *pWndPrev, *pWndChild;
if (pWndPrev = CWnd::FindWindow(lpszUniqueClass,NULL))
An application will normally initialize by executing the code in such a way that the sequence, as indicated in the
comments (which are alphabetical top-to-bottom, although the code doesn't execute that way) is as follows:
Consider the sequence shown below of two applications initializing.
||Application instance 1
||Application instance 2|
||E FindWindow() => FALSE
||E FindWindow() => FALSE|
||D new CMainFrame
||D new CMainFrame|
||A (in PreCreateWindow)
||A (in PreCreateWindow)|
Note that this successfully passes the test! At time 2, when Application instance 1 calls
FindWindow, there is no other window instance. So FindWindow returns
FALSE, indicating there is no second instance. So the initialization sequence proceeds. But meanwhile Application instance 2 is initializing. At time 4, when it executes
FindWindow, there is no other window instance of the desired type. So
FALSE, and Application instance 2 knows it is the only instance. So it continues to initialize. So by the time Application instance 1 creates the window that
FindWindow would have found, the test is long since past when Application instance 2 would have found it. And we get two running instances!
If you think this can't happen, you are living in a different world than the real one. I saw it happen. Repeatedly. Approximately one time out of three.
I found this out when a client had a very fast Pentium and had configured the Win98 desktop to launch-on-single-click. Years of conditioning had taught the user to double-click the icon, so whenever he double-clicked the icon, he launched two copies of the app. And far too often, both came up!
So why does the
CreateMutex method work? Doesn't it suffer from the same problem? No, because the creation of a Mutex is an atomic operation in the kernel. The creation of a Mutex is guaranteed to complete before any other thread can successfully create a Mutex. Therefore, we are absolutely guaranteed that the creation of the object and the test for its existence are a single operation, not separated by thousands or tens of thousands preemptible instructions as the
FindWindow or (as I discuss in the next section)
Daniel Lohmann, who has made significant contributions to this article, also points out that in terms of "uniqueness",
FindWindow has a problem in that it enumerates only windows in the same desktop as the calling thread. Therefore, if there is another instance running on another desktop you won't find it to pop it up!
SendMessage: Race conditions
One of the most common folkloristic methods (and one I used for years, alas) is to use
EnumWindows, do a
SendMessage to each window, and look at the return result from
SendMessage. What you send is a Registered Window Message (see my essay on Message Management), and if you receive this message you return
TRUE. All other windows will not understand this and return
FALSE. This turns out to be deeply flawed in a variety of ways.
Note that this method always worked in Win16 because it used cooperative multitasking. It is the preemptive multitasking of Win32 that makes this method fail. And it does.
SendMessage can hang indefinitely. But if the thread that owns the handle is blocked, on a Semaphore, a Mutex, an Event, an I/O operation, or some other manner, the
SendMessage will block until that thread frees up and runs. But this may never happen.. So you haven't gained any reliability.
You can solve this by using
SendMessageTimeout. This more-or-less works. You will typically choose a short timeout, for example about 200ms.
But it gets worse.
Microsoft, in violation of all known Windows specifications, has created an application that does not pass messages it doesn't understand to
DefWindowProc, which would return 0 for any message it does not understand. Instead, they have a component, apparently associated with Personal Web Server, which has the truly antisocial property of returning 1 for every message sent to its top-level window, whether it understands it or not. So you can't rely on a zero meaning it is not your app.
Well, this could be solved. When I needed to do this for another reason, I ended up having to return the registered window message value, which avoids the Microsoft blunder.
So we've solved the problem of timeouts and bogus messages. We know not to depend on the caption contents, and probably want to avoid worrying about the Window class name. So why doesn't this work?
Because of a much more fundamental problem: a race condition. Just like the one described in the previous section.
The code did an
EnumWindows loop and for each
HWND it did a
SendMessage. So what happened was that application instance 1 searched for another instance of itself, didn't find one, and proceeded to come up. Meanwhile, application instance 2 searched for an instance of itself, but since instance 1 had not yet come up and created its own main window, instance 2 did not find a conflicting instance, and it proceeded to come up. Using a scheme similar to the table I used to demonstrate why the basic
FindWindow method doesn't work, you can show that this method will fail for the same reason.
This is the most fundamental failure of this mechanism, and a reason it cannot be used.
Another method which has been proposed is to use a shared variable between all instances of the application. This can be done by creating a shared data segment. The technique is of the form:
#pragma comment(linker, "/SECTION:.shr,RWS")
HWND hGlobal = NULL;
HANDLE hMutexOneInstance = ::CreateMutex( NULL, TRUE,
AlreadyRunning = (GetLastError() == ERROR_ALREADY_EXISTS);
if (hMutexOneInstance != NULL)
if ( AlreadyRunning )
HWND hOther = g_hWnd;
if (hOther != NULL)
return FALSE; }
This almost works. It avoids the fundamental race condition, because the
CreateMutex call is an atomic operation. No matter what the relative timings of the two processes are, exactly one of them will create the Mutex first, and the other will get the
ERROR_ALREADY_EXISTS. Note that I used
GUIDGEN to get a guaranteed-unique ID.
The use of the shared variable presents a problem. This shared variable is only shared with other instances from the same executable. This means that if you run a version of the debug executable, and a version of the release executable, one cannot find the other's window to pop it up. Thus, when an instance finds that it is a duplicate (they still share the same Mutex name), it cannot find its other instance to pop it up. This will confuse you.
The code, however, is simpler than mine; it doesn't need the
EnumWindows handler, or the code inside it, or a user-defined Registered Window Message, or a handler in
I don't understand why the Mutex is created in owned mode (the second parameter is
TRUE). The Microsoft documentation even says that when doing a
CreateMutex from separate threads that this parameter must always be
FALSE because otherwise it is impossible to determine which thread actually owns the Mutex. Since this Mutex is not used in any way in the code, the use of the
TRUE parameter doesn't seem to have any value.
Daniel Lohmann has observed that shared memory is shared even if the processes run under different user accounts, as long as the instances are on the same machine. Of course it's also shared if the instances reside on different desktops. Therefore, the use of shared variables has marginal value--and may even be harmful--when you generalize the notion as he indicates in his suggestions in the next section.
Daniel Lohmann pointed out the fundamental defect of the above mechanism. Although it is reliable, it is not complete, in that it addresses only one of the three possible meanings of "unique instance".
- Avoiding multiple instances started in the same user session.
- Avoiding multiple instances started in the same desktop.
- Avoiding multiple instances started in any session of the same user account.
- Avoiding multiple instances started on the same machine.
In particular, he points out that my way of creating the Mutex name uses a system-global name, guaranteed to be unique for the application, but which is known to all users, sessions, and desktops. Note that this raises the same issue with respect to any use of global names for Mutexes, Semaphores, Events, and even shared memory-mapped files: the assumption that a single name is valid depends upon your interpretation of the above three points. Thus, if you are building a system that uses synchronization primitives and which requires a solution other than (d), you will have to apply the techniques below to the synchronization primitive naming as well.
He points out that in the Terminal Server edition of NT (which is built into Windows 2000), the kernel no longer has a single "global" namespace, but in fact each Terminal Server session has a private namespace. System services share a common namespace for what is called the "console session". He points out that "this all results in consuming much more memory and making some programming tasks quite tricky, but the result is that every user logged into the Terminal Server is able to start its E-Mail client".
There's another little fix he made to my code:
CreateMutex() call fails with
ERROR_ACCESS_DENIED if the Mutex was created in another user's session. This comes from passing
NULL for the
SECURITY_ATTRIBUTES which results in default security settings. The typical default DACL allows only CREATOR/OWNER and SYSTEM access to the object.
His proposed solution is to extend the name of the Mutex beyond the GUID technique I use, to address the solutions of (a)-(c). He writes:
"I start with (b) because it is simpler. Using
GetThreadDesktop() you get a handle to the desktop your thread is running on. Passing this to
GetUserObjectInformation(), you get the name of the desktop, which is unique".
"Even (c) is quite easy. The solution is to add the current users account name. Using
GetUserName() you get the current users account name. You should qualify it with the current users domain, which can be determined using
USERDOMAIN as variable name."
"For (a) it's a little bit more complicated. You have to open the process token using
OpenProcessToken(). Pass this token to
GetTokenInformation() to retrieve a
TOKEN_STATISTICS structure. The
AuthenticationId member of this structure, a 64-bit number (coded as an
LUID), contains the unique id of the login session. Convert this into a string".
Based on his description, I created the following subroutine and header file. Note that for any given application, you must decide at compile time which exclusion option you want; for example, if you want to have the application unique to a desktop, choose the
UNIQUE_TO_DESKTOP option to generate the key. If you have an application that chooses this dynamically, you can have one running in the system, thinking it is unique, and one running on the desktop, thinking it is unique. I built a little project to test this code, which you can download at the top of this article.
#define UNIQUE_TO_SYSTEM 0
#define UNIQUE_TO_DESKTOP 1
#define UNIQUE_TO_SESSION 2
#define UNIQUE_TO_TRUSTEE 3
CString createExclusionName(LPCTSTR GUID, UINT kind = UNIQUE_TO_SYSTEM);
CString createExclusionName(LPCTSTR GUID, UINT kind)
CString s = GUID;
HDESK desktop = GetThreadDesktop(GetCurrentThreadId());
BOOL result = GetUserObjectInformation(desktop, UOI_NAME, NULL, 0, &len);
DWORD err = ::GetLastError();
if(!result && err == ERROR_INSUFFICIENT_BUFFER)
LPBYTE data = new BYTE[len];
result = GetUserObjectInformation(desktop, UOI_NAME, data, len, &len);
s += _T("-");
s += (LPCTSTR)data;
delete [ ] data;
s += _T("-Win9x");
CString s = GUID;
BOOL result = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
GetTokenInformation(token, TokenStatistics, NULL, 0, &len);
LPBYTE data = new BYTE[len];
GetTokenInformation(token, TokenStatistics, data, len, &len);
LUID uid = ((PTOKEN_STATISTICS)data)->AuthenticationId;
delete [ ] data;
t.Format(_T("-%08x%08x"), uid.HighPart, uid.LowPart);
return s + t;
CString s = GUID;
#define NAMELENGTH 64
DWORD userNameLength = NAMELENGTH;
DWORD domainNameLength = NAMELENGTH;
domainNameLength = ExpandEnvironmentStrings(_T("%USERDOMAIN%"),
t.Format(_T("-%s-%s"), domainName, userName);
s += t;
Back in the original example, replace the string which I hardwired into the
::CreateMutex call with a call on
createExclusionName with the desired specification to get a correctly-formatted unique name to use for the Mutex.
The traditional methods of multiple-instance detection, including those documented by Microsoft, are deeply flawed. There is only one method that is known to work correctly, creating a kernel object, and it is documented here in two of the many possible forms that this technique could use.
The notion of "unique" should be well-defined; in most cases, it means "unique to a session" and perhaps "unique to a desktop", and the naive approach can actually keep independent users from running concurrently on an NT system.
A special Wave Of The Flounder Fin to Daniel Lohmann for his excellent suggestions to the article! A pure-C version of his code, which is slightly different from what I implemented, can be found here. His Web Site is worth looking at if you are into multiple desktops and Terminal Server.
The views expressed in these essays are those of the author, and in no way represent, nor are they endorsed by, Microsoft.
Send mail to email@example.com with questions or comments about this article.
Copyright © 1999 <!--webbot bot="Substitution" s-variable="CompanyLongName" startspan -->CompanyLongName<!--webbot bot="Substitution" endspan i-checksum="22147" --> All Rights Reserved.