2

For every windows service you can define "recover policy" indicating what to do in case of a failure.

This works for when the service fail to start, but how can I trigger "failure" if the service started successfully but did something wrong while running? I tried to throw exception but the service controller just hides it, I tried to set exit code to 1 and call Stop() but it just stops gracefully..

Is there a way to tell windows "this service has crashed and want to use the recovery policy" from code and after it had successfully started? If its not possible to trigger the recover policy after started that's OK, but whats the best way to stop while indicating windows there was an error?

Thanks,

Ronen Ness
  • 9,923
  • 4
  • 33
  • 50
  • 2
    Step outside your fluffy managed world and dereference a null pointer. – IInspectable Feb 05 '20 at 15:30
  • 1
    @IInspectable lol, thanks that's an interesting approach, but I prefer something more clean. You gave me an idea to try Environment.Exit(1) though, might work.. – Ronen Ness Feb 05 '20 at 15:33
  • 1
    That *is* clean. You need something that raises an SEH exception. Accessing inaccessible memory will do that. The memory at address 0 is guaranteed to be inaccessible. Dereferencing a null pointer will cleanly raise an SEH exception with error code 0xC0000005. – IInspectable Feb 05 '20 at 15:44
  • @IInspectable to clarify, by "unclean" I meant that if for example I'll check out events viewer, I'll see an error about "access violation", and not the logical error I want to emit (for example "agent died with exit code -5"). I could always create my own event right before it, but I still feel like this solution might cause confusion, especially with different monitoring tools that listen to these events. – Ronen Ness Feb 05 '20 at 15:48
  • The recover policy only kicks in after abnormal process termination. You cannot test your policy without a fatal error. If you must, I'm sure you can raise an SEH exception with your own custom error code. – IInspectable Feb 05 '20 at 16:00
  • @IInspectable thanks for the info and ideas, I'll check this out and see if I can create custom SEH errors. – Ronen Ness Feb 05 '20 at 16:06

1 Answers1

0

As per MSDN documentation the correct way is to exit the service with a non-zero return code.

Environment.Exit(1);

If you have configured the recovery options for your service, in Windows System logs you will then see a message such as this one:

... service terminated unexpectedly. The following corrective action will be taken in 60000 miliseconds: Restart the service.

Vedran
  • 10,369
  • 5
  • 50
  • 57