I've written a service for Windows XP+ in python using the With Extended Service Notifications example code. It works great for detecting user logon/logoff lock screen, and other events. The problem is that it never executes shutdown events and gracefully stops the service upon reboot/shutdown. It stays alive through logon/logoff events as well as starting up again after the reboot. Any help would be appreciated.

I don't want to use RegisterServiceCtrlHandlerEx and handle console signals if I can help it--services have this functionality built in, I've just mangled it somehow.

Here's the code:

from os.path import splitext, abspath
from sys import modules

import win32serviceutil
import win32service
import win32event
import win32api
import win32security
import win32ts

class Service(win32serviceutil.ServiceFramework):
  _svc_name_ = '_unNamed'
  _svc_display_name_ = '_Service Template'

  def __init__(self, *args):
    win32serviceutil.ServiceFramework.__init__(self, *args)
    self.log('Initializing Service')
    self.stop_event = win32event.CreateEvent(None, 0, 0, None)
    self.server = None

  def log(self, msg):
    import servicemanager
    servicemanager.LogInfoMsg(str(msg))
  def logErr(self, msg):
    import servicemanager
    servicemanager.LogErrorMsg(str(msg))
  def logWarn(self, msg):
    import servicemanager
    servicemanager.LogWarningMsg(str(msg))

  def sleep(self, sec):
    win32api.Sleep(sec*1000, True)

  def GetAcceptedControls(self):
    # Accept SESSION_CHANGE control
    rc = win32serviceutil.ServiceFramework.GetAcceptedControls(self)
    rc |= win32service.SERVICE_ACCEPT_SESSIONCHANGE
    rc |= win32service.SERVICE_ACCEPT_SHUTDOWN
    return rc

  def GetUserInfo(self, sess_id):
    sessions = win32security.LsaEnumerateLogonSessions()[:-5]
    for sn in sessions:
      sn_info = win32security.LsaGetLog
Edit
Report