Avoiding two processes of the same application in Pascal

1

What is the most feasible way to identify the processes of my application in memory and terminate them if there is more than one execution. I use the Lazarus IDE platform (looks like Delphi), which supports the object-oriented Pascal programming language.

OBS: Even though there are different process names, you can identify my application.

    
asked by anonymous 09.12.2014 / 03:43

2 answers

3

The UniqueInstance component can do this work for you, just use it a component in the main form, manipulates the Identifier property (used to identify your application) and activates it.

You can also do this by using the CreateMutex() > to identify the application, if the function succeeds the return value will be the identity of the application, otherwise a null value.

If this identifier already exists before calling the function, the return will be the identifier for the existing object, in this case, when calling the function GetLastError() , the return value will be ERROR_ALREADY_EXISTS . This in practice would look something like this:

var
  mutex: THandle;
  ID: string;
begin
  ID:= 'MyAppUniqueID';
  mutex := CreateMutex(nil, False, PChar(ID));

  if GetLastError = ERROR_ALREADY_EXISTS then begin
    Application.Terminate;
  end;
end;

The code snippet above can be used in the OnCreate() event of the main form. To release the identifier you can use the CloseHandle() > in the event OnClose() or OnDestroy() , for this the variable mutex would have to be a global variable.

    
10.12.2014 / 04:19
1

The function CreateSemaphore Windows. If the GetLastError function says that a semaphore with that name already exists, it is already running. Otherwise, no.

Relevant excerpt from function documentation:

  

Return value

     

If the function succeeds, the return value is a handle to the   semaphore object. If the named semaphore object existed before the   function call, the function returns to handle the existing object   and GetLastError returns ERROR_ALREADY_EXISTS. If the function fails,   the return value is NULL. To get extended error information, call   GetLastError.

Example usage:

repeat
sleep(10000);
createsemaphore("umnomequalquer");
until getlasterror <> ERROR_ALREADY_EXISTS;
    
09.12.2014 / 05:12