[Twisted-Python] Running twistd and tac files as Windows service

Phil Mayers p.mayers at imperial.ac.uk
Wed Oct 24 08:14:19 EDT 2012


n 24/10/12 12:33, Michael Schlenker wrote:
> Am 24.10.2012 11:01, schrieb Phil Mayers:
>> On 10/24/2012 08:43 AM, John Aherne wrote:
>>
>>> I don't have much idea about signalhandlers but I assume the one I am
>>> interested in here is to stop ControlC. The others might need to stay
>>> on. I'm not too sure about that without knowing more about windows
>>> services and how they react to these signals.
>>
>> No, you need more than that removed. Otherwise you get a "signal" (can't
>> remember which - SIGBRK?) when the logged-in workstation logs off, which
>> terminates your twisted services. Very confusing.
>
> There are no signals on windows.

But Python for windows certain calls "signal()" handlers in response to 
certain events, in certain configurations. Whether they're actually 
"signals" is kind of moot, though interesting.

>
> But what you are talking about is the SetConsoleCtrlHandler function.
> http://docs.activestate.com/activepython/2.4/pywin32/win32api__SetConsoleCtrlHandler_meth.html
> http://msdn.microsoft.com/en-us/library/windows/desktop/ms686016%28v=vs.85%29.aspx
>
> Thats relevant if your process has a console, e.g. is not a GUI app.
> (pythonw.exe vs. python.exe). If you run as a GUI app you might get a
> WM_QUERYENDSESSION or similar message.
>
> You get a CTRL_LOGOFF_EVENT when a user on the machine logs off and you
> run as a subprocess of a service and need to ignore it. The service
> itself should deal with this already.

Interesting.

I've just looked over the code we've got. It actually does something 
rather more involved than I'd first thought. Specifcally, the "ntsvc.py" 
code is pure-python, no Twisted. It actually runs the Twisted daemon as 
a sub-process, like this:

import os

class MyService(win32serviceutil.ServiceFramework):
      """NT Service."""

      _svc_name_ = "opimport-wrap"
      _svc_display_name_ = "Marval opimport wrapper"

      def SvcDoRun(self):
          self.childServer = Popen([
            "c:/python25/pythonw.exe",SCRIPT,"svc"
          ])
          self.childServer.wait()

...and the Twisted script does this:


def main():
   args = sys.argv[1:]
   if args and args[0]=='svc':
     as_service = True
   else:
     as_service = False

   ...

   if as_service:
     log.startLogging(some_log_observer)
     reactor.run(installSignalHandlers=0)
   else:
     log.startLogging(sys.stderr)
     reactor.run()

My memory is hazy on this, but if I recall correctly the main reason it 
works this way is that I can execute the twisted script directly from 
the console (for debugging) or via the service wrapper.

Are you suggesting that if I change that subprocess to use "python.exe" 
versus "pythonw.exe" I would not need to disable the signal handlers?

Cheers,
Phil



More information about the Twisted-Python mailing list