pub struct Service { /* private fields */ }Expand description
A struct that represents a system service.
The instances of the Service can be obtained via ServiceManager.
Implementations§
Source§impl Service
impl Service
Sourcepub fn raw_handle(&self) -> SC_HANDLE
pub fn raw_handle(&self) -> SC_HANDLE
Provides access to the underlying system service handle
Sourcepub fn start<S: AsRef<OsStr>>(&self, service_arguments: &[S]) -> Result<()>
pub fn start<S: AsRef<OsStr>>(&self, service_arguments: &[S]) -> Result<()>
Start the service.
§Example
use std::ffi::OsStr;
use windows_service::service::ServiceAccess;
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)?;
let my_service = manager.open_service("my_service", ServiceAccess::START)?;
my_service.start(&[OsStr::new("Started from Rust!")])?;Sourcepub fn stop(&self) -> Result<ServiceStatus>
pub fn stop(&self) -> Result<ServiceStatus>
Stop the service.
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::{
4 thread::sleep,
5 time::{Duration, Instant},
6 };
7
8 use windows_service::{
9 service::{ServiceAccess, ServiceState},
10 service_manager::{ServiceManager, ServiceManagerAccess},
11 };
12 use windows_sys::Win32::Foundation::ERROR_SERVICE_DOES_NOT_EXIST;
13
14 let manager_access = ServiceManagerAccess::CONNECT;
15 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
16
17 let service_access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE;
18 let service = service_manager.open_service("ping_service", service_access)?;
19
20 // The service will be marked for deletion as long as this function call succeeds.
21 // However, it will not be deleted from the database until it is stopped and all open handles to it are closed.
22 service.delete()?;
23 // Our handle to it is not closed yet. So we can still query it.
24 if service.query_status()?.current_state != ServiceState::Stopped {
25 // If the service cannot be stopped, it will be deleted when the system restarts.
26 service.stop()?;
27 }
28 // Explicitly close our open handle to the service. This is automatically called when `service` goes out of scope.
29 drop(service);
30
31 // Win32 API does not give us a way to wait for service deletion.
32 // To check if the service is deleted from the database, we have to poll it ourselves.
33 let start = Instant::now();
34 let timeout = Duration::from_secs(5);
35 while start.elapsed() < timeout {
36 if let Err(windows_service::Error::Winapi(e)) =
37 service_manager.open_service("ping_service", ServiceAccess::QUERY_STATUS)
38 {
39 if e.raw_os_error() == Some(ERROR_SERVICE_DOES_NOT_EXIST as i32) {
40 println!("ping_service is deleted.");
41 return Ok(());
42 }
43 }
44 sleep(Duration::from_secs(1));
45 }
46 println!("ping_service is marked for deletion.");
47
48 Ok(())
49}Sourcepub fn pause(&self) -> Result<ServiceStatus>
pub fn pause(&self) -> Result<ServiceStatus>
Pause the service.
§Example
use windows_service::service::ServiceAccess;
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)?;
let my_service = manager.open_service("my_service", ServiceAccess::PAUSE_CONTINUE)?;
my_service.pause()?;Examples found in repository?
12fn main() -> windows_service::Result<()> {
13 use std::env;
14 use windows_service::{
15 service::ServiceAccess,
16 service_manager::{ServiceManager, ServiceManagerAccess},
17 };
18
19 let service_name = env::args().nth(1).unwrap_or("Winmgmt".to_owned());
20
21 let manager_access = ServiceManagerAccess::CONNECT;
22 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
23
24 let service = service_manager.open_service(&service_name, ServiceAccess::PAUSE_CONTINUE)?;
25
26 println!("Pause {}", service_name);
27 let paused_state = service.pause()?;
28 println!("{:?}", paused_state.current_state);
29
30 println!("Resume {}", service_name);
31 let resumed_state = service.resume()?;
32 println!("{:?}", resumed_state.current_state);
33
34 Ok(())
35}Sourcepub fn resume(&self) -> Result<ServiceStatus>
pub fn resume(&self) -> Result<ServiceStatus>
Resume the paused service.
Examples found in repository?
12fn main() -> windows_service::Result<()> {
13 use std::env;
14 use windows_service::{
15 service::ServiceAccess,
16 service_manager::{ServiceManager, ServiceManagerAccess},
17 };
18
19 let service_name = env::args().nth(1).unwrap_or("Winmgmt".to_owned());
20
21 let manager_access = ServiceManagerAccess::CONNECT;
22 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
23
24 let service = service_manager.open_service(&service_name, ServiceAccess::PAUSE_CONTINUE)?;
25
26 println!("Pause {}", service_name);
27 let paused_state = service.pause()?;
28 println!("{:?}", paused_state.current_state);
29
30 println!("Resume {}", service_name);
31 let resumed_state = service.resume()?;
32 println!("{:?}", resumed_state.current_state);
33
34 Ok(())
35}Sourcepub fn notify(&self, code: UserEventCode) -> Result<ServiceStatus>
pub fn notify(&self, code: UserEventCode) -> Result<ServiceStatus>
Send user-defined control code.
Examples found in repository?
11fn main() -> windows_service::Result<()> {
12 use std::env;
13 use windows_service::{
14 service::{ServiceAccess, UserEventCode},
15 service_manager::{ServiceManager, ServiceManagerAccess},
16 };
17
18 let service_name = env::args().nth(1).unwrap_or("ping_service".to_owned());
19
20 let manager_access = ServiceManagerAccess::CONNECT;
21 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
22
23 let service = service_manager.open_service(
24 &service_name,
25 ServiceAccess::PAUSE_CONTINUE | ServiceAccess::USER_DEFINED_CONTROL,
26 )?;
27
28 const NO_OP: UserEventCode = unsafe { UserEventCode::from_unchecked(128) };
29 const CUSTOM_STOP: UserEventCode = unsafe { UserEventCode::from_unchecked(130) };
30
31 println!("Send `NO_OP` notification to {}", service_name);
32 let state = service.notify(NO_OP)?;
33 println!("{:?}", state.current_state);
34
35 println!("Send `CUSTOM_STOP` notification to {}", service_name);
36 let state = service.notify(CUSTOM_STOP)?;
37 println!("{:?}", state.current_state);
38
39 Ok(())
40}Sourcepub fn query_status(&self) -> Result<ServiceStatus>
pub fn query_status(&self) -> Result<ServiceStatus>
Get the service status from the system.
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::{
4 thread::sleep,
5 time::{Duration, Instant},
6 };
7
8 use windows_service::{
9 service::{ServiceAccess, ServiceState},
10 service_manager::{ServiceManager, ServiceManagerAccess},
11 };
12 use windows_sys::Win32::Foundation::ERROR_SERVICE_DOES_NOT_EXIST;
13
14 let manager_access = ServiceManagerAccess::CONNECT;
15 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
16
17 let service_access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE;
18 let service = service_manager.open_service("ping_service", service_access)?;
19
20 // The service will be marked for deletion as long as this function call succeeds.
21 // However, it will not be deleted from the database until it is stopped and all open handles to it are closed.
22 service.delete()?;
23 // Our handle to it is not closed yet. So we can still query it.
24 if service.query_status()?.current_state != ServiceState::Stopped {
25 // If the service cannot be stopped, it will be deleted when the system restarts.
26 service.stop()?;
27 }
28 // Explicitly close our open handle to the service. This is automatically called when `service` goes out of scope.
29 drop(service);
30
31 // Win32 API does not give us a way to wait for service deletion.
32 // To check if the service is deleted from the database, we have to poll it ourselves.
33 let start = Instant::now();
34 let timeout = Duration::from_secs(5);
35 while start.elapsed() < timeout {
36 if let Err(windows_service::Error::Winapi(e)) =
37 service_manager.open_service("ping_service", ServiceAccess::QUERY_STATUS)
38 {
39 if e.raw_os_error() == Some(ERROR_SERVICE_DOES_NOT_EXIST as i32) {
40 println!("ping_service is deleted.");
41 return Ok(());
42 }
43 }
44 sleep(Duration::from_secs(1));
45 }
46 println!("ping_service is marked for deletion.");
47
48 Ok(())
49}Sourcepub fn delete(&self) -> Result<()>
pub fn delete(&self) -> Result<()>
Mark the service for deletion from the service control manager database.
The database entry is not removed until all open handles to the service have been closed and the service is stopped. If the service is not or cannot be stopped, the database entry is removed when the system is restarted. This function will return an error if the service has already been marked for deletion.
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::{
4 thread::sleep,
5 time::{Duration, Instant},
6 };
7
8 use windows_service::{
9 service::{ServiceAccess, ServiceState},
10 service_manager::{ServiceManager, ServiceManagerAccess},
11 };
12 use windows_sys::Win32::Foundation::ERROR_SERVICE_DOES_NOT_EXIST;
13
14 let manager_access = ServiceManagerAccess::CONNECT;
15 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
16
17 let service_access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE;
18 let service = service_manager.open_service("ping_service", service_access)?;
19
20 // The service will be marked for deletion as long as this function call succeeds.
21 // However, it will not be deleted from the database until it is stopped and all open handles to it are closed.
22 service.delete()?;
23 // Our handle to it is not closed yet. So we can still query it.
24 if service.query_status()?.current_state != ServiceState::Stopped {
25 // If the service cannot be stopped, it will be deleted when the system restarts.
26 service.stop()?;
27 }
28 // Explicitly close our open handle to the service. This is automatically called when `service` goes out of scope.
29 drop(service);
30
31 // Win32 API does not give us a way to wait for service deletion.
32 // To check if the service is deleted from the database, we have to poll it ourselves.
33 let start = Instant::now();
34 let timeout = Duration::from_secs(5);
35 while start.elapsed() < timeout {
36 if let Err(windows_service::Error::Winapi(e)) =
37 service_manager.open_service("ping_service", ServiceAccess::QUERY_STATUS)
38 {
39 if e.raw_os_error() == Some(ERROR_SERVICE_DOES_NOT_EXIST as i32) {
40 println!("ping_service is deleted.");
41 return Ok(());
42 }
43 }
44 sleep(Duration::from_secs(1));
45 }
46 println!("ping_service is marked for deletion.");
47
48 Ok(())
49}More examples
2fn main() -> windows_service::Result<()> {
3 use std::ffi::OsString;
4 use std::time::Duration;
5 use windows_service::{
6 service::{
7 ServiceAccess, ServiceAction, ServiceActionType, ServiceErrorControl,
8 ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType,
9 ServiceType,
10 },
11 service_manager::{ServiceManager, ServiceManagerAccess},
12 };
13
14 const SERVICE_NAME: &str = "service_failure_actions_example";
15
16 let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
17 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
18
19 let service_binary_path = ::std::env::current_exe()
20 .unwrap()
21 .with_file_name("service_failure_actions.exe");
22
23 let service_info = ServiceInfo {
24 name: OsString::from(SERVICE_NAME),
25 display_name: OsString::from("Service Failure Actions Example"),
26 service_type: ServiceType::OWN_PROCESS,
27 start_type: ServiceStartType::OnDemand,
28 error_control: ServiceErrorControl::Normal,
29 executable_path: service_binary_path,
30 launch_arguments: vec![],
31 dependencies: vec![],
32 account_name: None, // run as System
33 account_password: None,
34 };
35
36 let service_access = ServiceAccess::QUERY_CONFIG
37 | ServiceAccess::CHANGE_CONFIG
38 | ServiceAccess::START
39 | ServiceAccess::DELETE;
40
41 println!("Create or open the service {}", SERVICE_NAME);
42 let service = service_manager
43 .create_service(&service_info, service_access)
44 .or(service_manager.open_service(SERVICE_NAME, service_access))?;
45
46 let actions = vec![
47 ServiceAction {
48 action_type: ServiceActionType::Restart,
49 delay: Duration::from_secs(5),
50 },
51 ServiceAction {
52 action_type: ServiceActionType::RunCommand,
53 delay: Duration::from_secs(10),
54 },
55 ServiceAction {
56 action_type: ServiceActionType::None,
57 delay: Duration::default(),
58 },
59 ];
60
61 println!("Update failure actions");
62 let failure_actions = ServiceFailureActions {
63 reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400 * 2)),
64 reboot_msg: None,
65 command: Some(OsString::from("ping 127.0.0.1")),
66 actions: Some(actions),
67 };
68 service.update_failure_actions(failure_actions)?;
69
70 println!("Query failure actions");
71 let updated_failure_actions = service.get_failure_actions()?;
72 println!("{:#?}", updated_failure_actions);
73
74 println!("Enable failure actions on non-crash failures");
75 service.set_failure_actions_on_non_crash_failures(true)?;
76
77 println!("Query failure actions on non-crash failures enabled");
78 let failure_actions_flag = service.get_failure_actions_on_non_crash_failures()?;
79 println!(
80 "Failure actions on non-crash failures enabled: {}",
81 failure_actions_flag
82 );
83
84 println!("Delete the service {}", SERVICE_NAME);
85 service.delete()?;
86
87 Ok(())
88}Sourcepub fn query_config(&self) -> Result<ServiceConfig>
pub fn query_config(&self) -> Result<ServiceConfig>
Get the service config from the system.
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::env;
4 use windows_service::{
5 service::ServiceAccess,
6 service_manager::{ServiceManager, ServiceManagerAccess},
7 };
8
9 let service_name = env::args().nth(1).unwrap_or("netlogon".to_owned());
10
11 let manager_access = ServiceManagerAccess::CONNECT;
12 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
13
14 let service = service_manager.open_service(service_name, ServiceAccess::QUERY_CONFIG)?;
15
16 let config = service.query_config()?;
17 println!("{:#?}", config);
18 Ok(())
19}Sourcepub fn change_config(&self, service_info: &ServiceInfo) -> Result<()>
pub fn change_config(&self, service_info: &ServiceInfo) -> Result<()>
Update the service config. Caveat: You cannot reset the account name/password by passing NULL.
This implementation does not currently expose the full flexibility of the
ChangeServiceConfigW API. When calling the API it’s possible to pass NULL in place of
any of the string arguments to indicate that they should not be updated.
If we wanted to support this we wouldn’t be able to reuse the ServiceInfo struct.
Sourcepub fn set_failure_actions_on_non_crash_failures(
&self,
enabled: bool,
) -> Result<()>
pub fn set_failure_actions_on_non_crash_failures( &self, enabled: bool, ) -> Result<()>
Configure failure actions to run when the service terminates before reporting the
ServiceState::Stopped back to the system or if it exits with non-zero
ServiceExitCode.
Please refer to MSDN for more info:
https://docs.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-_service_failure_actions_flag
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::ffi::OsString;
4 use std::time::Duration;
5 use windows_service::{
6 service::{
7 ServiceAccess, ServiceAction, ServiceActionType, ServiceErrorControl,
8 ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType,
9 ServiceType,
10 },
11 service_manager::{ServiceManager, ServiceManagerAccess},
12 };
13
14 const SERVICE_NAME: &str = "service_failure_actions_example";
15
16 let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
17 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
18
19 let service_binary_path = ::std::env::current_exe()
20 .unwrap()
21 .with_file_name("service_failure_actions.exe");
22
23 let service_info = ServiceInfo {
24 name: OsString::from(SERVICE_NAME),
25 display_name: OsString::from("Service Failure Actions Example"),
26 service_type: ServiceType::OWN_PROCESS,
27 start_type: ServiceStartType::OnDemand,
28 error_control: ServiceErrorControl::Normal,
29 executable_path: service_binary_path,
30 launch_arguments: vec![],
31 dependencies: vec![],
32 account_name: None, // run as System
33 account_password: None,
34 };
35
36 let service_access = ServiceAccess::QUERY_CONFIG
37 | ServiceAccess::CHANGE_CONFIG
38 | ServiceAccess::START
39 | ServiceAccess::DELETE;
40
41 println!("Create or open the service {}", SERVICE_NAME);
42 let service = service_manager
43 .create_service(&service_info, service_access)
44 .or(service_manager.open_service(SERVICE_NAME, service_access))?;
45
46 let actions = vec![
47 ServiceAction {
48 action_type: ServiceActionType::Restart,
49 delay: Duration::from_secs(5),
50 },
51 ServiceAction {
52 action_type: ServiceActionType::RunCommand,
53 delay: Duration::from_secs(10),
54 },
55 ServiceAction {
56 action_type: ServiceActionType::None,
57 delay: Duration::default(),
58 },
59 ];
60
61 println!("Update failure actions");
62 let failure_actions = ServiceFailureActions {
63 reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400 * 2)),
64 reboot_msg: None,
65 command: Some(OsString::from("ping 127.0.0.1")),
66 actions: Some(actions),
67 };
68 service.update_failure_actions(failure_actions)?;
69
70 println!("Query failure actions");
71 let updated_failure_actions = service.get_failure_actions()?;
72 println!("{:#?}", updated_failure_actions);
73
74 println!("Enable failure actions on non-crash failures");
75 service.set_failure_actions_on_non_crash_failures(true)?;
76
77 println!("Query failure actions on non-crash failures enabled");
78 let failure_actions_flag = service.get_failure_actions_on_non_crash_failures()?;
79 println!(
80 "Failure actions on non-crash failures enabled: {}",
81 failure_actions_flag
82 );
83
84 println!("Delete the service {}", SERVICE_NAME);
85 service.delete()?;
86
87 Ok(())
88}Sourcepub fn get_failure_actions_on_non_crash_failures(&self) -> Result<bool>
pub fn get_failure_actions_on_non_crash_failures(&self) -> Result<bool>
Query the system for the boolean indication that the service is configured to run failure actions on non-crash failures.
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::ffi::OsString;
4 use std::time::Duration;
5 use windows_service::{
6 service::{
7 ServiceAccess, ServiceAction, ServiceActionType, ServiceErrorControl,
8 ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType,
9 ServiceType,
10 },
11 service_manager::{ServiceManager, ServiceManagerAccess},
12 };
13
14 const SERVICE_NAME: &str = "service_failure_actions_example";
15
16 let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
17 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
18
19 let service_binary_path = ::std::env::current_exe()
20 .unwrap()
21 .with_file_name("service_failure_actions.exe");
22
23 let service_info = ServiceInfo {
24 name: OsString::from(SERVICE_NAME),
25 display_name: OsString::from("Service Failure Actions Example"),
26 service_type: ServiceType::OWN_PROCESS,
27 start_type: ServiceStartType::OnDemand,
28 error_control: ServiceErrorControl::Normal,
29 executable_path: service_binary_path,
30 launch_arguments: vec![],
31 dependencies: vec![],
32 account_name: None, // run as System
33 account_password: None,
34 };
35
36 let service_access = ServiceAccess::QUERY_CONFIG
37 | ServiceAccess::CHANGE_CONFIG
38 | ServiceAccess::START
39 | ServiceAccess::DELETE;
40
41 println!("Create or open the service {}", SERVICE_NAME);
42 let service = service_manager
43 .create_service(&service_info, service_access)
44 .or(service_manager.open_service(SERVICE_NAME, service_access))?;
45
46 let actions = vec![
47 ServiceAction {
48 action_type: ServiceActionType::Restart,
49 delay: Duration::from_secs(5),
50 },
51 ServiceAction {
52 action_type: ServiceActionType::RunCommand,
53 delay: Duration::from_secs(10),
54 },
55 ServiceAction {
56 action_type: ServiceActionType::None,
57 delay: Duration::default(),
58 },
59 ];
60
61 println!("Update failure actions");
62 let failure_actions = ServiceFailureActions {
63 reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400 * 2)),
64 reboot_msg: None,
65 command: Some(OsString::from("ping 127.0.0.1")),
66 actions: Some(actions),
67 };
68 service.update_failure_actions(failure_actions)?;
69
70 println!("Query failure actions");
71 let updated_failure_actions = service.get_failure_actions()?;
72 println!("{:#?}", updated_failure_actions);
73
74 println!("Enable failure actions on non-crash failures");
75 service.set_failure_actions_on_non_crash_failures(true)?;
76
77 println!("Query failure actions on non-crash failures enabled");
78 let failure_actions_flag = service.get_failure_actions_on_non_crash_failures()?;
79 println!(
80 "Failure actions on non-crash failures enabled: {}",
81 failure_actions_flag
82 );
83
84 println!("Delete the service {}", SERVICE_NAME);
85 service.delete()?;
86
87 Ok(())
88}Sourcepub fn get_config_service_sid_info(&self) -> Result<ServiceSidType>
pub fn get_config_service_sid_info(&self) -> Result<ServiceSidType>
Query the system for the service’s SID type information.
The service must be open with the ServiceAccess::QUERY_CONFIG
access permission prior to calling this method.
Sourcepub fn set_config_service_sid_info(
&self,
service_sid_type: ServiceSidType,
) -> Result<()>
pub fn set_config_service_sid_info( &self, service_sid_type: ServiceSidType, ) -> Result<()>
Require the system to set the service’s SID type information to the provided value.
The service must be open with the ServiceAccess::CHANGE_CONFIG
access permission prior to calling this method.
Sourcepub fn get_failure_actions(&self) -> Result<ServiceFailureActions>
pub fn get_failure_actions(&self) -> Result<ServiceFailureActions>
Query the configured failure actions for the service.
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::ffi::OsString;
4 use std::time::Duration;
5 use windows_service::{
6 service::{
7 ServiceAccess, ServiceAction, ServiceActionType, ServiceErrorControl,
8 ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType,
9 ServiceType,
10 },
11 service_manager::{ServiceManager, ServiceManagerAccess},
12 };
13
14 const SERVICE_NAME: &str = "service_failure_actions_example";
15
16 let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
17 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
18
19 let service_binary_path = ::std::env::current_exe()
20 .unwrap()
21 .with_file_name("service_failure_actions.exe");
22
23 let service_info = ServiceInfo {
24 name: OsString::from(SERVICE_NAME),
25 display_name: OsString::from("Service Failure Actions Example"),
26 service_type: ServiceType::OWN_PROCESS,
27 start_type: ServiceStartType::OnDemand,
28 error_control: ServiceErrorControl::Normal,
29 executable_path: service_binary_path,
30 launch_arguments: vec![],
31 dependencies: vec![],
32 account_name: None, // run as System
33 account_password: None,
34 };
35
36 let service_access = ServiceAccess::QUERY_CONFIG
37 | ServiceAccess::CHANGE_CONFIG
38 | ServiceAccess::START
39 | ServiceAccess::DELETE;
40
41 println!("Create or open the service {}", SERVICE_NAME);
42 let service = service_manager
43 .create_service(&service_info, service_access)
44 .or(service_manager.open_service(SERVICE_NAME, service_access))?;
45
46 let actions = vec![
47 ServiceAction {
48 action_type: ServiceActionType::Restart,
49 delay: Duration::from_secs(5),
50 },
51 ServiceAction {
52 action_type: ServiceActionType::RunCommand,
53 delay: Duration::from_secs(10),
54 },
55 ServiceAction {
56 action_type: ServiceActionType::None,
57 delay: Duration::default(),
58 },
59 ];
60
61 println!("Update failure actions");
62 let failure_actions = ServiceFailureActions {
63 reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400 * 2)),
64 reboot_msg: None,
65 command: Some(OsString::from("ping 127.0.0.1")),
66 actions: Some(actions),
67 };
68 service.update_failure_actions(failure_actions)?;
69
70 println!("Query failure actions");
71 let updated_failure_actions = service.get_failure_actions()?;
72 println!("{:#?}", updated_failure_actions);
73
74 println!("Enable failure actions on non-crash failures");
75 service.set_failure_actions_on_non_crash_failures(true)?;
76
77 println!("Query failure actions on non-crash failures enabled");
78 let failure_actions_flag = service.get_failure_actions_on_non_crash_failures()?;
79 println!(
80 "Failure actions on non-crash failures enabled: {}",
81 failure_actions_flag
82 );
83
84 println!("Delete the service {}", SERVICE_NAME);
85 service.delete()?;
86
87 Ok(())
88}Sourcepub fn update_failure_actions(
&self,
update: ServiceFailureActions,
) -> Result<()>
pub fn update_failure_actions( &self, update: ServiceFailureActions, ) -> Result<()>
Update failure actions.
Pass None for optional fields to keep the corresponding fields unchanged, or pass an empty
value to reset them.
§Example
use std::ffi::OsString;
use std::time::Duration;
use windows_service::service::{
ServiceAccess, ServiceAction, ServiceActionType, ServiceFailureActions,
ServiceFailureResetPeriod,
};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)?;
let my_service = manager.open_service(
"my_service",
ServiceAccess::START | ServiceAccess::CHANGE_CONFIG,
)?;
let actions = vec![
ServiceAction {
action_type: ServiceActionType::Restart,
delay: Duration::from_secs(5),
},
ServiceAction {
action_type: ServiceActionType::RunCommand,
delay: Duration::from_secs(10),
},
ServiceAction {
action_type: ServiceActionType::None,
delay: Duration::default(),
},
];
let failure_actions = ServiceFailureActions {
reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400)),
reboot_msg: None,
command: Some(OsString::from("ping 127.0.0.1")),
actions: Some(actions),
};
my_service.update_failure_actions(failure_actions)?;Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::ffi::OsString;
4 use std::time::Duration;
5 use windows_service::{
6 service::{
7 ServiceAccess, ServiceAction, ServiceActionType, ServiceErrorControl,
8 ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType,
9 ServiceType,
10 },
11 service_manager::{ServiceManager, ServiceManagerAccess},
12 };
13
14 const SERVICE_NAME: &str = "service_failure_actions_example";
15
16 let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
17 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
18
19 let service_binary_path = ::std::env::current_exe()
20 .unwrap()
21 .with_file_name("service_failure_actions.exe");
22
23 let service_info = ServiceInfo {
24 name: OsString::from(SERVICE_NAME),
25 display_name: OsString::from("Service Failure Actions Example"),
26 service_type: ServiceType::OWN_PROCESS,
27 start_type: ServiceStartType::OnDemand,
28 error_control: ServiceErrorControl::Normal,
29 executable_path: service_binary_path,
30 launch_arguments: vec![],
31 dependencies: vec![],
32 account_name: None, // run as System
33 account_password: None,
34 };
35
36 let service_access = ServiceAccess::QUERY_CONFIG
37 | ServiceAccess::CHANGE_CONFIG
38 | ServiceAccess::START
39 | ServiceAccess::DELETE;
40
41 println!("Create or open the service {}", SERVICE_NAME);
42 let service = service_manager
43 .create_service(&service_info, service_access)
44 .or(service_manager.open_service(SERVICE_NAME, service_access))?;
45
46 let actions = vec![
47 ServiceAction {
48 action_type: ServiceActionType::Restart,
49 delay: Duration::from_secs(5),
50 },
51 ServiceAction {
52 action_type: ServiceActionType::RunCommand,
53 delay: Duration::from_secs(10),
54 },
55 ServiceAction {
56 action_type: ServiceActionType::None,
57 delay: Duration::default(),
58 },
59 ];
60
61 println!("Update failure actions");
62 let failure_actions = ServiceFailureActions {
63 reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400 * 2)),
64 reboot_msg: None,
65 command: Some(OsString::from("ping 127.0.0.1")),
66 actions: Some(actions),
67 };
68 service.update_failure_actions(failure_actions)?;
69
70 println!("Query failure actions");
71 let updated_failure_actions = service.get_failure_actions()?;
72 println!("{:#?}", updated_failure_actions);
73
74 println!("Enable failure actions on non-crash failures");
75 service.set_failure_actions_on_non_crash_failures(true)?;
76
77 println!("Query failure actions on non-crash failures enabled");
78 let failure_actions_flag = service.get_failure_actions_on_non_crash_failures()?;
79 println!(
80 "Failure actions on non-crash failures enabled: {}",
81 failure_actions_flag
82 );
83
84 println!("Delete the service {}", SERVICE_NAME);
85 service.delete()?;
86
87 Ok(())
88}Sourcepub fn set_description(&self, description: impl AsRef<OsStr>) -> Result<()>
pub fn set_description(&self, description: impl AsRef<OsStr>) -> Result<()>
Set service description.
Required permission: ServiceAccess::CHANGE_CONFIG.
Examples found in repository?
2fn main() -> windows_service::Result<()> {
3 use std::ffi::OsString;
4 use windows_service::{
5 service::{ServiceAccess, ServiceErrorControl, ServiceInfo, ServiceStartType, ServiceType},
6 service_manager::{ServiceManager, ServiceManagerAccess},
7 };
8
9 let manager_access = ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE;
10 let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
11
12 // This example installs the service defined in `examples/ping_service.rs`.
13 // In the real world code you would set the executable path to point to your own binary
14 // that implements windows service.
15 let service_binary_path = ::std::env::current_exe()
16 .unwrap()
17 .with_file_name("ping_service.exe");
18
19 let service_info = ServiceInfo {
20 name: OsString::from("ping_service"),
21 display_name: OsString::from("Ping service"),
22 service_type: ServiceType::OWN_PROCESS,
23 start_type: ServiceStartType::OnDemand,
24 error_control: ServiceErrorControl::Normal,
25 executable_path: service_binary_path,
26 launch_arguments: vec![],
27 dependencies: vec![],
28 account_name: None, // run as System
29 account_password: None,
30 };
31 let service = service_manager.create_service(&service_info, ServiceAccess::CHANGE_CONFIG)?;
32 service.set_description("Windows service example from windows-service-rs")?;
33 Ok(())
34}Sourcepub fn set_delayed_auto_start(&self, delayed: bool) -> Result<()>
pub fn set_delayed_auto_start(&self, delayed: bool) -> Result<()>
Set if an auto-start service should be delayed.
If true, the service is started after other auto-start services are started plus a short delay. Otherwise, the service is started during system boot. The default is false. This setting is ignored unless the service is an auto-start service.
Required permission: ServiceAccess::CHANGE_CONFIG.
Sourcepub fn set_preshutdown_timeout(&self, timeout: Duration) -> Result<()>
pub fn set_preshutdown_timeout(&self, timeout: Duration) -> Result<()>
Set the preshutdown timeout value of the service.
When the system prepares to shutdown, the service control manager will send ServiceControl::Preshutdown
to any service that accepts ServiceControlAccept::PRESHUTDOWN and block shutdown until either the
service is stopped or the preshutdown timeout has elapsed. The default value is 180 seconds on releases
prior to Windows 10 build 15063, and 10 seconds afterwards. This value is irrelevant unless the service
handles ServiceControl::Preshutdown.
Panics if the specified timeout is too large to fit as milliseconds in a u32.
Required permission: ServiceAccess::CHANGE_CONFIG.