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
RestartApplication in Windows service
Re: RestartApplication in Windows service
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.
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.
Re: RestartApplication in Windows service
This is what I have here:
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.
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;
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.