马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
Rust编写Windows服务
编写Windows服务可选语言许多, 此中C#最简朴。本着练手Rust语言,实验用Rust编写一个服务。
一:Windows服务步调大抵原理
参考官网C/C++创建服务流程
https://learn.microsoft.com/zh-cn/windows/win32/services/service-program-tasks
- 编写服务步调的main函数
- main函数中,添补数据结构 DispatchTable: [[服务名,ServiceMain函数], [NULL, NULL]]
- 调用StartServiceCtrlDispatcher( DispatchTable )
- int __cdecl _tmain(int argc, TCHAR *argv[])
- {
-
-
- SERVICE_TABLE_ENTRY DispatchTable[] =
- {
-
-
- {
-
- SVCNAME, (LPSERVICE_MAIN_FUNCTION) SvcMain },
- {
-
- NULL, NULL }
- };
- if (!StartServiceCtrlDispatcher( DispatchTable ))
- {
-
-
- SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
- }
- }
复制代码
- 编写 ServiceMain 函数
- 注册控制处理处罚函数 RegisterServiceCtrlHandler(SvcCtrlHandler )
- 设置服务状态,SERVICE_START_PENDING
- 做一些准备工作,好比初始化日记/注册事故等
- 设置服务状态,SERVICE_START_RUNNING
- 开始loop处理处罚我们自己的代码(loop循环中可以担当3中注册的事故,当关照制止时退出循环)
- 编写控件处理处罚步调函数
- 担当事故管理器发送的消息并处理处罚,好比收到SERVICE_CONTROL_STOP时,利用3中注册的事故句柄发送制止事故
二:Rust中编写windows服务
借用第三方库 windows-service = "0.7.0"
https://crates.io/crates/windows-service
参考windows-service中ping-service示例提取了一个模板,只有更换编写两处/* */代码
- use std::{
-
-
- ffi::OsString,
- sync::mpsc,
- time::Duration,
- };
- use windows_service::{
-
-
- define_windows_service,
- service::{
-
-
- ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus,
- ServiceType,
- },
- service_control_handler::{
-
- self, ServiceControlHandlerResult},
- service_dispatcher,
- };
- static SERVICE_NAME: &str = "Rust Demo Service";
- fn main() -> Result<(), windows_service::Error> {
-
-
- service_dispatcher::start(SERVICE_NAME, ffi_service_main)?;
- Ok(())
- }
- define_windows_service!(ffi_service_main, my_service_main);
- fn my_service_main(arguments: Vec<OsString>) {
-
-
- let _ = arguments;
-
- /*
- 这里服务还没开始, 可以填写初始化日志
文件等操作 - */
-
- let (shutdown_tx, shutdown_rx) = mpsc::channel();
- // 对应SvcCtrlHandler
- let _event_handler = move |control_event| -> ServiceControlHandlerResult {
-
-
- match control_event {
-
-
- ServiceControl
复制代码 |