Categories
Delphi

Running two instances of the same Delphi Service

Recently there was a need to run two instances of the same service written in Delphi on the same server. While you can manually changed the service name in the registry or via the “sc” command, the service will not start up correctly unless the service name matches the¬†TService.Name.

To get around this you can pass the name of the service as a parameter to the executable and dynamically set the Name and DisplayName properties when the service is created.

function GetParamValue( const ASwitch: string; var AValue: string ): Boolean;
var
  LIndex : Integer;
begin
  Result := False;
  for LIndex := 1 to ParamCount do
    if ( StartsText( ASwitch, ParamStr( LIndex ) ) ) then begin
      Result := True;
      AValue := ReplaceText( ParamStr( LIndex ), ASwitch, '' );
    end;
end;

procedure TYourService.ServiceAfterInstall(Sender: TService);
var
  LRegistry : TRegistry;
begin
  LRegistry := TRegistry.Create();
  try
    LRegistry.RootKey := HKEY_LOCAL_MACHINE;
    if ( LRegistry.OpenKey( 'SYSTEMCurrentControlSetServices' + Name, False ) ) then begin
      LRegistry.WriteString( 'ImagePath', ParamStr(0) + ' /name=' + Name );
    end;
  finally
    LRegistry.Free();
  end;
end;

procedure TYourService.ServiceCreate(Sender: TObject);
var
  LNewName  : string;
begin
  if ( GetParamValue( '/name=', LNewName ) ) then begin
    Name          := LNewName;
    DisplayName   := LNewName;
  end;
end;

The AfterInstall event makes sure that the /name parameter is passed to the service each time it starts up.

This should make your Delphi Service more flexible!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.