It should not be possible to run multiple instances of my application. Therefore the project source contains:
CreateMutex (nil, False, PChar (ID));
if (GetLastEr
hi take a look a the following article by Zarko Gajic - there you will get some ideas, sample code and even a whole component to use.
hth, reinhard
(beating the sleep idea)
if you want to make sure the original process is really terminated/closed before you create the mutex, then one idea is to pass the PID to the new process (command line is the easiest, any other IPC method works as well), then use OpenProcess(SYNCHRONIZE, false, pid) and WaitForSingleObject (I'd use a loop with a timeout (100 ms is a good value) and act accordingly if the original process takes too long to close)
What I ended up doing, beside the above, was to also create a RestartSelf procedure in the same unit with the mutex, and do the logic there, in order to keep the single instance and restart logic in the same place (the parameter being hardcoded, you don't want hardcoded stuff to be scattered around your application(s).
Your ReleaseMutex is probably failing since you're passing 'False' for 'bInitialOwner' while calling CreateMutex. Either have the initial ownership of the mutex, or call CloseHandle instead of 'ReleaseMutex' passing your mutex handle.
Include in your ShellExecute some parameter, for example, /WaitForShutDown and create one more mutex. In your program, before the initialization, for example, in its .dpr file, insert something like:
if (Pos('/WaitForShutDown', CmdLine) <> 0) then WaitForSingleObject(ShutDownMutexHandle, INFINITE);
Also, in your program, after all the finalizations and releasing your common resources, include something like
ReleaseMutex(ShutDownMutexHandle);
You could pass a command line argument like "restart" and run a Sleep() before you try to acquire the Mutex or try to acquire the mutex in a loop that sleeps a while.
Also you could set up communication between both processes, but that might be overkill.
Why can't you just release the mutex before attempting to restart? If by some chance another instance gets going before the one you explicitly invoke with the restart that doesn't matter, you'll still have your app up and running again with whatever changes effected that required the restart. I don't think you need any of the complexity of the other solutions.