RestartApplication in Windows service

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

RestartApplication in Windows service

Post by mszpcb »


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,
Site Admin
Posts: 10330
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.
Posts: 62
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);
  FileName: string;
  Content: TStringList;
  FileName := FileGetTempName('SV');
  FileName := ChangeFileExt(FileName, '.bat');

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


  ShellExecute(0, nil, PChar(FileName), nil, nil, SW_HIDE);
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