Window服务启动时会发生什么?

时间:2016-07-27 22:37:32

标签: python windows service multiprocessing

我正在用python编写一个Windows服务,并使用pyinstaller将其打包成可执行文件。 python脚本将包含具有必要重写方法的服务子类以及用于某些套接字通信的MessageServer类以及显示简单消息框。由于Windows中的交互式服务限制,我将MessageServer分开。我想弄清楚的是当你从GUI或CLI(net start)启动服务时会发生什么?它只是用start参数执行服务的.exe,还是只访问其中的一部分代码?

我会发布我正在使用的代码,但请记住,这远不是我想成为真实的东西......只是用它来测试一些想法。

import win32serviceutil
import win32service
import win32event
import servicemanager
import win32timezone
import win32api
import win32con

import sys
import time
import random

import multiprocessing

svc_name = "testSvc"
TIMEOUT = 6000


class TesterService(win32serviceutil.ServiceFramework):
    _svc_name_ = svc_name
    _svc_display_name_ = "test service"
    _svc_description_ = "This service is for testing purposes"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        global sm
        while True:
            stop_signal = win32event.WaitForSingleObject(self.hWaitStop, TIMEOUT)

            try:
                if stop_signal == win32event.WAIT_OBJECT_0:
                    break
                else:
                    if sm == 0:
                        sm = 1
            except RuntimeError as details:
                print(details)


class MessageServer(object):
    def __init__(self):
        self._messages_ = ["msg-1", "msg-2", "msg-3", "msg-4", "msg-5"]
        self._serve_msg_(self._messages_)

    def _serve_msg_(self, msgs):
        t = 0
        while t < 36:
            time.sleep(6)
            t += 6
            win32api.MessageBox(
                None,
                msgs[random.randint(0, 4)],
                "test message box",
                win32con.MB_ICONHAND
            )


class MsgSrvProcess(multiprocessing.Process):
    def __init__(self, name="Ptest"):
        multiprocessing.Process.__init__(self)
        self.name = name

    def run(self):
        MessageServer()


sm = 0
if __name__ == "__main__":
    multiprocessing.freeze_support()

    if len(sys.argv) == 1:
        servicemanager.Initialize(svc_name, None)
        servicemanager.PrepareToHostSingle(TesterService)
        servicemanager.StartServiceCtrlDispatcher()

    else:
        win32serviceutil.HandleCommandLine(TesterService)
    c = 0
    while c < 18:
        c += 6
        if sm == 1:
            p1 = MsgSrvProcess()
            p1.start()
            p1.join()
        else: sm = 1
        time.sleep(6)
    print("exiting")

0 个答案:

没有答案