PDA

View Full Version : How to prevent from running multiple application instances?



Chebmaster
23-05-2006, 01:05 PM
The Delphi method (via InstanceHandle) didn't work in FPC.

Ok, I solved the problem for Windows (se below), but how to do the same for Unix? Does anybody know?

Note: don't suggest me to create a small file and check if it exists. The method should work even if the app. crashed without a chance to cleanup.


unit preventmultipleinstances;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils {$ifdef win32}, Windows{$endif};
function ThisIsAnOnlyInstance: boolean;
implementation
{$ifdef win32}
var
M: THandle;
Di: boolean = false;
function ThisIsAnOnlyInstance: boolean;
var N: string;
begin
Result:=True;
N:='SingleInstancEMutex'
+ ChangeFileExt(ExtractFileName(ParamStr(0)),'');
M:=OpenMutex(MUTEX_MODIFY_STATE, False, PChar(N));
if M = 0 then M:=CreateMutex(nil, True, PChar(N))
else begin
if WaitForSingleObject(M, 0) <> WAIT_ABANDONED
then Result:=False;
end;
Di:=Result;
end;
{$else}
function ThisIsAnOnlyInstance: boolean;
begin
Result:=True;
end;
{$endif}
finalization
{$ifdef win32}
Try
if Di then ReleaseMutex(M);
Except End;
{$else}

{$endif}
end.

AthenaOfDelphi
23-05-2006, 01:16 PM
One option, although its not particularly nice, is to open a server port on 127.0.0.1 at the start of your app... if you can open it then you're the only one running... if you can't, the app is already running.

The file idea isn't such a bad one actually... whats wrong with opening a file and keeping the handle open... if you can open the file for writing, then you should be the only one running... if you can't another process already has the file opened. If the app crashes out, the handle should be cleaned up by the OS, thus your app doesn't actually have to do anything other than try and create the file when it starts.

That is a nicer way of doing it than the socket way as it doesn't really have any serious security issues (as far as I know) and it should work on any platform.

Just my thoughts.

Chebmaster
24-05-2006, 01:01 AM
if you can open the file for writing, then you should be the only one running...
Hmm... Why didn't I think of it myself?.. Thanks, I'll try that.

technomage
24-05-2006, 08:23 AM
On Windows systems there is the concept of a GlobalAtom , I don't have the code at the moment but it is a nice way of detecting previous instances of an application.

Traveler
24-05-2006, 10:51 AM
I did a quick search on GlobalAtom, as I'm not familiar with that myself.
There's been a question at Delphi pages (http://www.delphipages.com/threads/thread.cfm?ID=24029&G=24027)that explains a thing or two about it. Comes with code too. :)

technomage
24-05-2006, 11:04 AM
I have some code at work that uses GlobalAtom to detect if a app is running. I'll try and dig it out and post an example. :D