tags:

views:

1185

answers:

8

I need to make sure that user can run only one instance of my program at a time.
Which means, that I have to check programatically, whether the same program is already running, and quit in such case.

The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instance of the program would check for this file and exit if it found it.
The trouble is, that the program must always exit gracefully and be able to delete the file it created, for this to work. In case of, say, power outage, the lock file remains in place and the program can't be started again.

To solve this, I decided to store the first program's process ID into the lock file and when another instance starts, it checks if the PID from the file is attached to some running process.
If the file doesn't exist, is empty, or the PID doesn't correspond to any existing process, the program continues to run and writes its own PID to the file.

This seems to work quite fine - even after an unexpected shutdown, the chance that the (now obsolete) process ID will be associated with some other program, seems to be quite low.

But it still doesn't feel right (there is a chance of getting locked by some unrelated process) and working with process IDs seems to go beyond the standard C++ and probably isn't very portable either.

So, is there another (more clean and secure) way of doing this? Ideally one that would work with the ISO 98 C++ standard and on Windows and *nix alike.
If it cannot be done platform-independently, Linux/Unix is a priority for me.

+3  A: 

I actually use exactly the process you describe, and it works fine except for the edge case that happens when you suddenly run out of disk space and can no longer create files.

The "correct" way to do this is probably to use shared memory: http://www.cs.cf.ac.uk/Dave/C/node27.html

SquareCog
+18  A: 

There are several methods you can use to accomplish only allowing one instance of your application:

Method 1: Global synchronization object or memory

It's usually done by creating a named global mutex or event. If it is already created, then you know the program is already running.

For example in windows you could do:

    #define APPLICATION_INSTANCE_MUTEX_NAME "{BA49C45E-B29A-4359-A07C-51B65B5571AD}"

    //Make sure at most one instance of the tool is running
    HANDLE hMutexOneInstance(::CreateMutex( NULL, TRUE, APPLICATION_INSTANCE_MUTEX_NAME));
    bool bAlreadyRunning((::GetLastError() == ERROR_ALREADY_EXISTS));
    if (hMutexOneInstance == NULL || bAlreadyRunning)
    {
     if(hMutexOneInstance)
     {
      ::ReleaseMutex(hMutexOneInstance);
      ::CloseHandle(hMutexOneInstance);
     }
     throw std::exception("The application is already running");
    }

Method 2: Locking a file, second program can't open the file, so it's open

You could also exclusively open a file by locking it on application open. If the file is already exclusively opened, and your application cannot receive a file handle, then that means the program is already running. On windows you'd simply not specify sharing flags FILE_SHARE_WRITE on the file you're opening with CreateFile API. On linux you'd use flock.

Method 3: Search for process name:

You could enumerate the active processes and search for one with your process name.

Brian R. Bondy
If two people copy your code they might end up with the same APPLICATION_INSTANCE_MUTEX_NAME :->
Hugh Allen
ya they should use their own unique string :) I did think of changing it from mine though :)
Brian R. Bondy
+3  A: 

Your method of writing the process pid to a file is a common one that is used in many different established applications. In fact, if you look in your /var/run directory right now I bet you'll find several *.pid files already.

As you say, it's not 100% robust because there is chance of the pids getting confused. I have heard of programs using flock() to lock an application-specific file that will automatically be unlocked by the OS when the process exits, but this method is more platform-specific and less transparent.

Greg Hewgill
I think one reason so many UNIX apps still use lock files is because file locking on NFS may or may not be worth anything: http://en.wikipedia.org/wiki/File_locking#Problems
bk1e
A: 

I don't have a good solution, but two thoughts:

  1. You could add a ping capability to query the other process and make sure it's not an unrelated process. Firefox does something similar on Linux and doesn't start a new instance when one is already running.

  2. If you use a signal handler, you can ensure the pid file is deleted on all but a kill -9

jvasak
A: 

I scan the process list looking for the name of my apps executable with matching command line parameters then exit if there is a match.

My app can run more than once, but I don't want it running the same config file at the same time.

Obviously, this is Windows specific, but the same concept is pretty easy on any *NIX system even without specific libraries simply by opening the shell command 'ps -ef' or a variation and looking for your app.

   '*************************************************************************
   '     Sub: CheckForProcess()
   '  Author: Ron Savage
   '    Date: 10/31/2007
   '
   ' This routine checks for a running process of this app with the same
   ' command line parameters.
   '*************************************************************************
   Private Function CheckForProcess(ByVal processText As String) As Boolean
      Dim isRunning As Boolean = False
      Dim search As New ManagementObjectSearcher("SELECT * FROM Win32_process")
      Dim info As ManagementObject
      Dim procName As String = ""
      Dim procId As String = ""
      Dim procCommandLine As String = ""

      For Each info In search.Get()
         If (IsNothing(info.Properties("Name").Value)) Then procName = "NULL" Else procName = Split(info.Properties("Name").Value.ToString, ".")(0)
         If (IsNothing(info.Properties("ProcessId").Value)) Then procId = "NULL" Else procId = info.Properties("ProcessId").Value.ToString
         If (IsNothing(info.Properties("CommandLine").Value)) Then procCommandLine = "NULL" Else procCommandLine = info.Properties("CommandLine").Value.ToString

         If (Not procId.Equals(Me.processId) And procName.Equals(processName) And procCommandLine.Contains(processText)) Then
            isRunning = True
         End If
      Next

      Return (isRunning)
   End Function

Ron

Ron Savage
This suffers from the race condition of having another process started between querying the system for it and returning to the caller saying it wasn't found. Using the mutex approach is one way around it.
Johann Gerell
+1  A: 

If you want something that's bog standard, then using a file as a 'lock' is pretty much the way to go. It does have the drawback that you mentioned (if your app doesn't clean up, restarting can be an issue).

This method is used by quite a few applications, but the only one I can recall off the top of my head is VMware. And yes, there are times when you have to go in and delete the '*.lck' when things get wedged.

Using a global mutex or other system object as mentioned by Brian Bondy is a better way to go, but these are platform specific, (unless you use some other library to abstract the platform specifics away).

Michael Burr
+3  A: 

It is very un-unix to prohibit multiple instances of a program to run.

If the program is, say, a network daemon, it doesn't need to actively prohibit multiple instances--only the first instance gets to listen to the socket, so subsequent instances bomb out automatically. If it is, say, an RDBMS, it doesn't need to actively prohibit multiple instances--only the first instance gets to open and lock the files. etc.

DrPizza
It's a program, that should run together with another daemon that behaves this way (because of the socket listening).Thus, I consider it a good idea to do the same - but I don't have any socket or database to use as a lock.
Tomas Sedovic
@Shadow: Can you ask the daemon?
wnoise
Can the daemon not enforce this all by its own, by only letting one program communicate with it (or do whatever it is that needs doing)?
DrPizza
I'm not exactly sure, it's a bit complicated. But I will look into that.
Tomas Sedovic
+2  A: 

Be careful, a single-instance program is its own denial of service.

The link decribes the security problem of single instance detection and suggests using a securable method so at least processes of lower rights can't exploit the problem.

Aardvark