Rust编写Windows服务

[复制链接]
发表于 2026-1-21 19:01:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
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 )   
      
  1. int __cdecl _tmain(int argc, TCHAR *argv[])
  2. {
  3.    
  4.    
  5.     SERVICE_TABLE_ENTRY DispatchTable[] =
  6.     {
  7.    
  8.    
  9.         {
  10.    
  11.     SVCNAME, (LPSERVICE_MAIN_FUNCTION) SvcMain },
  12.         {
  13.    
  14.     NULL, NULL }
  15.     };
  16.     if (!StartServiceCtrlDispatcher( DispatchTable ))
  17.     {
  18.    
  19.    
  20.         SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
  21.     }
  22. }
复制代码

      
  • 编写 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示例提取了一个模板,只有更换编写两处/* */代码
  1. use std::{
  2.    
  3.    
  4.     ffi::OsString,
  5.     sync::mpsc,
  6.     time::Duration,
  7. };
  8. use windows_service::{
  9.    
  10.    
  11.     define_windows_service,
  12.     service::{
  13.    
  14.    
  15.         ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus,
  16.         ServiceType,
  17.     },
  18.     service_control_handler::{
  19.    
  20.    self, ServiceControlHandlerResult},
  21.     service_dispatcher,
  22. };
  23. static SERVICE_NAME: &str = "Rust Demo Service";
  24. fn main() -> Result<(), windows_service::Error> {
  25.    
  26.    
  27.     service_dispatcher::start(SERVICE_NAME, ffi_service_main)?;
  28.     Ok(())
  29. }
  30. define_windows_service!(ffi_service_main, my_service_main);
  31. fn my_service_main(arguments: Vec<OsString>) {
  32.    
  33.    
  34.     let _ = arguments;
  35.         
  36.     /*
  37.             这里服务还没开始, 可以填写初始化日志日志文件等操作
  38.     */
  39.    
  40.     let (shutdown_tx, shutdown_rx) = mpsc::channel();
  41.     // 对应SvcCtrlHandler
  42.     let _event_handler = move |control_event| -> ServiceControlHandlerResult {
  43.    
  44.    
  45.         match control_event {
  46.    
  47.    
  48.             ServiceControl
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表