Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot stop Windows Service from example #104

Open
BrilllianD opened this issue May 26, 2023 · 1 comment
Open

Cannot stop Windows Service from example #104

BrilllianD opened this issue May 26, 2023 · 1 comment

Comments

@BrilllianD
Copy link

BrilllianD commented May 26, 2023

I make custom Windows Service from example, register by "sc" cmd, run it.
Then when trying to stop this, Windows raise error message "failed to stop service ... this service did not return an error".

I have try to find some code in this repo, but cannot find example how to handle it.

P.S.
thanks for any help

@RylBlue
Copy link

RylBlue commented Dec 24, 2024

Ran into this myself earlier, the solution is to set the program state to ServiceState::Stopped either during the event handler or shortly after returning from the event handler.

See this example which spawns a thread to set the service to ServiceState::Stopped in response to a ServiceControl::Stop request:

    let status_handler = Arc::new(Mutex::<Option<ServiceStatusHandle>>::new(None));
    
    let event_handler = move |control_event| -> ServiceControlHandlerResult {
        let to_return = match control_event {
            ServiceControl::Stop | ServiceControl::Interrogate => {
                ServiceControlHandlerResult::NoError
            }
            _ => ServiceControlHandlerResult::NotImplemented,
        };
        
        if let ServiceControl::Stop = control_event{
            let status_handler_clone = status_handler.clone();
            std::thread::spawn(move || {
                std::thread::sleep(Duration::from_millis(800));
                if let Ok(Some(h)) = status_handler_clone.lock().as_deref(){
                    let _ = h.set_service_status(ServiceStatus{
                       service_type: ServiceType::OWN_PROCESS,
                       current_state: ServiceState::Stopped,
                       controls_accepted: ServiceControlAccept::empty(),
                       exit_code: ServiceExitCode::Win32(0),
                       checkpoint: 0,
                       wait_hint: Duration::default(),
                       process_id: None 
                    });
                }
                //exit(0); 
            });
        }
        
        to_return
    };

Windows will also automatically shut down the service after this, so no need to invoke std::process::exit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants