manage.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build windows
  5. package main
  6. import (
  7. "fmt"
  8. "time"
  9. "golang.org/x/sys/windows/svc"
  10. "golang.org/x/sys/windows/svc/mgr"
  11. )
  12. func startService(name string) error {
  13. m, err := mgr.Connect()
  14. if err != nil {
  15. return err
  16. }
  17. defer m.Disconnect()
  18. s, err := m.OpenService(name)
  19. if err != nil {
  20. return fmt.Errorf("could not access service: %v", err)
  21. }
  22. defer s.Close()
  23. err = s.Start("is", "manual-started")
  24. if err != nil {
  25. return fmt.Errorf("could not start service: %v", err)
  26. }
  27. return nil
  28. }
  29. func controlService(name string, c svc.Cmd, to svc.State) error {
  30. m, err := mgr.Connect()
  31. if err != nil {
  32. return err
  33. }
  34. defer m.Disconnect()
  35. s, err := m.OpenService(name)
  36. if err != nil {
  37. return fmt.Errorf("could not access service: %v", err)
  38. }
  39. defer s.Close()
  40. status, err := s.Control(c)
  41. if err != nil {
  42. return fmt.Errorf("could not send control=%d: %v", c, err)
  43. }
  44. timeout := time.Now().Add(10 * time.Second)
  45. for status.State != to {
  46. if timeout.Before(time.Now()) {
  47. return fmt.Errorf("timeout waiting for service to go to state=%d", to)
  48. }
  49. time.Sleep(300 * time.Millisecond)
  50. status, err = s.Query()
  51. if err != nil {
  52. return fmt.Errorf("could not retrieve service status: %v", err)
  53. }
  54. }
  55. return nil
  56. }