RestartApplication in Windows service

delphi package - automated exception handling
Post Reply
mszpcb
Posts: 1
Joined: Thu Jul 13, 2017 4:08 pm

RestartApplication in Windows service

Post by mszpcb »

Hi,

I use MadExcept within a Windows service and want the service to be restartet in case of an exception. Unfortunately neigther setting "automatically restart application" in the configuration dialog nor calling procedure RestartApplication manually (this is my preferred method) seems to work: The service stops but does not come back to life again.
Are there any special settings required for services ("don't show anything" ist already selected)? Is there a way to restart the service with MadExcept?

Many thanks in advance,
Michael
madshi
Site Admin
Posts: 10754
Joined: Sun Mar 21, 2004 5:25 pm

Re: RestartApplication in Windows service

Post by madshi »

madExcept does not have built in support for restarting services. I don't even know which APIs would need to be called in order to achieve that. For normal applications I simply use "CreateProcess" + "TerminateProcess(myself)". This obviously won't work for services.

If you know how to restart services, you can use "RegisterExceptActionHandler(stDontSync)" to get notified about when the user presses the "restart application" button. In that situation you can then set "handled := true" in your callback function, and then perform the restarting yourself, using your own code.
obones
Posts: 66
Joined: Fri May 15, 2009 11:47 am

Re: RestartApplication in Windows service

Post by obones »

This is what I have here:

Code: Select all

procedure RestartService(const ServiceName: UnicodeString);
var
  FileName: string;
  Content: TStringList;
begin
  FileName := FileGetTempName('SV');
  DeleteFile(FileName);
  FileName := ChangeFileExt(FileName, '.bat');

  Content := TStringList.Create;
  try
    Content.Add('@echo off');
    Content.Add('ping -n 3 127.0.0.1 > NUL');
    Content.Add('net stop ' + ServiceName);
    Content.Add('ping -n 10 127.0.0.1 > NUL');
    Content.Add('taskkill /F /T /IM ' + ExtractFileName(ParamStr(0)));
    Content.Add('ping -n 3 127.0.0.1 > NUL');
    Content.Add('net start ' + ServiceName);
    Content.Add('del /F "%0"');

    Content.SaveToFile(FileName);
  finally
    Content.Free;
  end;

  ShellExecute(0, nil, PChar(FileName), nil, nil, SW_HIDE);
end;
Note that your exe still runs after this code is called, you may want to terminate it immediately.
And yes, the delays may be a bit too long for your liking, but it's to be on the "super safe" side of things.
Post Reply