-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstop.go
72 lines (63 loc) · 1.45 KB
/
stop.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package winservice
import (
"context"
"time"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/mgr"
)
// Stop issues a stop command to a service and waits for it to stop. It returns
// an error if it fails or the context is cancelled.
//
// Stop returns without error if the service is already stopped.
func Stop(ctx context.Context, name string) error {
m, err := mgr.Connect()
if err != nil {
return OpError{Op: "stop", Service: name, Err: err}
}
defer m.Disconnect()
if err := stopService(ctx, m, name); err != nil {
return OpError{Op: "stop", Service: name, Err: err}
}
return nil
}
func stopService(ctx context.Context, m *mgr.Mgr, name string) error {
s, err := m.OpenService(name)
if err != nil {
return err
}
defer s.Close()
status, err := s.Control(svc.Stop)
switch err {
case nil:
// The stop command was issued
case ErrServiceNotActive:
// The service is not running
return nil
case ErrServiceCannotAcceptControl:
// The service is in some state that can't accept a stop command
switch status.State {
case svc.StopPending:
// The stop is already pending, which is what we wanted anyway
default:
return err
}
default:
return err
}
ticker := time.NewTicker(PollingInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
status, err := s.Query()
if err != nil {
return err
}
if status.State == svc.Stopped {
return nil
}
}
}
}