Determine if only one instance is running

From Rosetta Code
Revision as of 17:28, 21 November 2008 by rosettacode>IanOsgood (Java, using ServerSocket as a mutex)
Task
Determine if only one instance is running
You are encouraged to solve this task according to the task description, using any language you may know.

This task is to determine if there is only one instance of an application running.

C++

Microsoft Windows

Works with: Windows version 2000 or later

This line needs to be near the top of the file (or in stdafx.h, if you use one.)

#include <afx.h>

You need a variable of type HANDLE with the same lifetime as your program. Perhaps as a member of your CWinApp object.

HANDLE mutex;

At the earliest possible point in your program, you need to initialize it and perform your check. "MyApp" should be a string unique to your application. See here for full details.

mutex = CreateMutex( NULL, TRUE, "MyApp" );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
{
     // There's another instance running.  What do you do?
}

Finally, near the end of your program, you need to close the mutex.

CloseHandle( mutex );

Java

<java>import java.io.*;

public class SingletonApp { private static final int PORT = 10356; // random large port number private static ServerSocket s;

// static initializer { try { s = new ServerSocket(PORT, 10, InetAddress.getLocalHost()); } catch (UnknownHostException e) { // shouldn't happen for localhost } catch (IOException e) { // port taken, so app is already running System.exit(0); } } // main() and rest of application... }</java>

Python

Linux (including cygwin) and Mac OSX Leopard

Works with: Python version 2.6

Must be run from an application, not the interpreter.

import __main__, os

def isOnlyInstance():
    # Determine if there are more than the current instance of the application
    # running at the current time. If not, return 0. If so, return 1.
    if not os.system('(( $(ps -ef | grep python | grep \'[' + \
    __main__.__file__[0] + ']' + __main__.__file__[1:len(__main__.__file__)] \
    + '\' | wc -l) > 1 ))'):
        return 0
    else:
        return 1

This is not a solution - one can run the same app by copying the code to another location. A solution may be a lock file or lock directory created by the first instance and hold while the first instance is running.

Visual Basic

Works with: Visual Basic version 6
 Dim onlyInstance as Boolean
 onlyInstance = not App.PrevInstance