Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Part 2: How Can I Allow Only One Running Instance of My Application?


Part 2: How Can I Allow Only One Running Instance of My Application?

Last issue, we looked at two ways to handle detecting another running instance of an application—using a unique window class and using a Win32 synchronization object. We continue exploring this problem by examining three additional techniques : the Running Object Table, Memory Mapped Files, and a Shared Data Segment. Here’s a look at each one.

Running Object Table

The Running Object Table (ROT as it is known in COM circles) is commonly used in OLE applications, but seldom used otherwise. Here is how MSDN defines the ROT:

A globally accessible table on each computer that keeps track of all COM objects in the running state that can be identified by a moniker. Moniker providers register an object in the table, which increments the object's reference count. Before the object can be destroyed, its moniker must be released from the table.

The beauty of the ROT (compared with its simpler cousin the Global Interface Table, or GIT) is that it is accessible across processes. This allows us to register a COM object in the ROT with a known name and then check to see if that object is there from additional application instances.

The trick with the ROT is dealing with monikers. If you’ve never had a chance to experience the joy of working with monikers, consider yourself fortunate. The built-in monikers such as item or file monikers are simple to work with, but may be to OLE-like for your needs. So you may be forced to implement the IMoniker interface in an object simply as a way to efficiently handle registering the real object with the ROT. This is more cumbersome than the GIT, which deal with interfaces. Since the problem deals with the same application knowing whether other instances of itself are running, you could get away with using an item or file moniker as a quick way of registering your object with the ROT. The challenge, then, becomes devising a format for the moniker name that makes sense for your application —it might be the application filename in the case of a file moniker, or a string such as “app name!filename” combination for an item moniker.

Of course, this approach makes the most sense if you already are using COM or OLE heavily in your application and have a ready-made object (such as the proverbial Application object) that you can register with the ROT.

Memory-Mapped Files

A memory-mapped file has the interesting property of being accessible across processes via its name. This allows one process to create a file in memory, write some data to it, and have that data read by another process, which opens the file in read mode. In our case, we don't really need to read and write data, we simply need to create a file in one process and then test for its existence in another.

Here is how this might look:

const LPCSTR MyUniqueMMF = "MyAppName;

BOOL CApp::InitInstance()
{
    HANDLE hFile = OpenFileMapping( FILE_MAP_READ, 
TRUE, 
MyUniqueMMF );
    if ( !hFile )
    {
m_hFile = CreateFileMapping(
INVALID_HANDLE_VALUE,
                            NULL,
                            PAGE_READWRITE,
                            0,
                            100,
                            MyUniqueMMF );
    }
    else
    {
        CloseHandle( hFile );
        return FALSE;
    }
}

Looking at this code carefully, you’ll notice that we attempt to open the named memory-mapped file first. If this fails, we assume we are the first instance so we go ahead and create the file. If we get a valid file handle from the call to OpenFileMapping, then we know there is an instance already running so we close the handle and exit.

This is a clean solution to the problem and may work well in many cases.

Shared Data Segment

This approach probably goes down as one of the more obscure ways to determine whether another instance is running. It harkens back to the pre-Win32 days when it was common to rely on the fact that DLLs could share data across instances because the DLL was loaded once, regardless of how many instances used it. Since under Win32, DLLs are mapped to each process space, this ability seemed to have been lost. But by using a little known #pragma directive, you can reenable this capability.

First, you'd create a DLL for your application whose purpose is to handle detecting another running instance. In this DLL, you'd create a C function that could be called from the application to check for another instance. Within the file containing this function, you'd add the following to the top of the file:

   #pragma data_seg(".MYDATA")<br>   BOOL alreadyRunning = FALSE;<br>   #pragma data_seg() <br>   #pragma comment(linker, "/SECTION:.MYDATA,RWS") 

This tells the compiler that the variable alreadyRunning will be located in a shared data segment within the DLL. The boolean variable would then be set to True in the C function as in the following:

BOOL IsAppRunning()
{
    BOOL bRunning = alreadyRunning;
    alreadyRunning = TRUE;
    return bRunning;
}

The #pragma comment(linker…) line tells the linker that the variables in the segment are to be shared and is required to make this technique work.

This approach would make sense if you were already building DLLs for your application and were using the Microsoft Visual C++ compiler. It wouldn’t work for other compilers since the #pragma commands are Microsoft-specific. It has the advantage of being very simple compared to some of the other approaches we’ve examined. You can learn more about this approach by reading Jeffrey Richter’s Advanced Windows NT book (which is a must-read for any serious Win32 developer).

Including the methods described in the previous newsletter, we’ve explored five different ways of approaching how to detect another running instance. There are undoubtedly other ways to do this, but this is a good set to get you started.


Mark M. Baker is the Chief of Research & Development at BNA Software located in Washington, D.C. He can be contacted at [email protected].


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.