1.服务程序的启动过程:
在启动自启服务之前,SCM创建一个管道作远程过程调用Pipe//Ntsvcs,
并创建一个线程来监听SCP的消息,然后通知它的初始化结束事件。
SCM通过由RegesterServiceProcess注册一个控制台应用程序关闭事件处理,
并向WIN32子系统注册来为系统关闭做准备。
通过调用SCM的ScAutoStartService来启动自启动服务(阶段性,启动前的检测工作包括
检测服务标志,依赖关系,是否为当前引导配置的一部分)。
然后确定要启动服务,SCM调用ScStartService函数。当ScStartService启动一个
WIN32服务的时候,会读取服务注册表(即服务数据库的内容)主键ImagePath
来确定来确定运行服务进程的文件,然后检测服务类型。。。
最后启动服务程序。
2.服务启动过程:
SERVICE_WIN32_SHARE_PROCESS类型的服务,在程序中进行公共初始化,
StartServiceCtrlDispatcher函数调用之前在主线程中完成初始化(安装服务),只要花费时间少于30秒。否则,当主线程
调用StartServiceCtrlDispatcher的时候必须创建另外的一个线程去完成公共初始化(安装服务)。
等待调用StartServiceCtrlDispatcher函数。
在规定时间内完成初始化,我们的主线程接下来
要创建一个同SCM的连接,这个创建的过程就是使服务进程的主线程成为SCP的主线程。
这是英文的说明
the main thread calls StartServiceCtrlDispatcher and becomes the service control dispatcher(MSDN)
The StartServiceCtrlDispatcher function connects the main thread of a service process to the service control manager,
which causes the thread to be the service control dispatcher thread for the calling process. (MSDN)
SCP的第一个功能:操作服务控制请求。
前面提到过,SCM通过命名管道控制这个线程(SCP)的请求(SCM<----SCP),并且发送控制请求给SCP(SCM---->SCP),然后SCP同过调用Handle函数响应(SCM---->SCP---->Handler),
并把结果返回给SCM(SCM<----SCP<----Handler),我们也可以直接控制SCP来向服务发送控制状态,比如说我们电脑中的“查看本地服务”,通过它可以启动或是停止服务
就是直接通过SCP发送控制请求给服务的Handler函数来操作的。下面是MSDN上的英文介绍:
The service control manager uses this connection to send control and service start requests to the main thread of the service process.
The main thread acts as a dispatcher by invoking the appropriate Handler function to handle control requests。
or by creating a new thread to execute the appropriate ServiceMain function when a new service is started. (msdn)
注意上面英文的最后一句即是SCP线程的第二个功能:by creating a new thread to execute the appropriate ServiceMain function when a new service is started。
当多个服务的时候,SCP创建一个新线程去执行ServiceMain函数,当一个新的服务开始的时候。
ServiceMain函数完成下列任务:
1.立刻调用RegisterServiceCtrlHandlerEx函数去注册服务的句柄控制请求,返回值就服务的状态句柄,
可以用来通知SCM服务的状态。即使让Handler函数和SCP联系起来,SCP把来自SCM的控制请求发送给Handler函数(即SCM--->SCP--->Handler)。
然后Handler函数通过SetServiceStatus函数把结果通过SERVICE_STATUS_HANDLE结构返回给SCM(即SCM<---SCP<---Handler)
register a control handler function with the control dispatcher.
This enables the control dispatcher to invoke the specified function when it receives control requests for this service.(MSDN)
2.完成初始化(即设置服务状态)。少于一秒,直接完成。如果大于一秒调用SetServiceStatus向SCM报告状态。
3.初始化完成,调用SetServiceStatus,在SERVICE_STATUS结构中指定服务状态为SERVICE_RUNNING.(意外情况,都调用SetServiceStatus,设置状态)
2没什么可说的,来说下3部的SetServiceStatus:
The SetServiceStatus function updates the service control manager's status information for the calling service.
MSDN中解释的很清楚,用来更新服务在SCM中的状态信息。具体过程大概是:把服务中当前状态,用新的状态更新。
所以SCP是控制服务应用程序的功能块,也是服务应用程序SCM之间的桥梁。
编写一个自起服务的笔记
最新推荐文章于 2023-06-27 16:27:33 发布