service.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 mgr
  6. import (
  7. "syscall"
  8. "golang.org/x/sys/windows"
  9. "golang.org/x/sys/windows/svc"
  10. )
  11. // TODO(brainman): Use EnumDependentServices to enumerate dependent services.
  12. // Service is used to access Windows service.
  13. type Service struct {
  14. Name string
  15. Handle windows.Handle
  16. }
  17. // Delete marks service s for deletion from the service control manager database.
  18. func (s *Service) Delete() error {
  19. return windows.DeleteService(s.Handle)
  20. }
  21. // Close relinquish access to the service s.
  22. func (s *Service) Close() error {
  23. return windows.CloseServiceHandle(s.Handle)
  24. }
  25. // Start starts service s.
  26. // args will be passed to svc.Handler.Execute.
  27. func (s *Service) Start(args ...string) error {
  28. var p **uint16
  29. if len(args) > 0 {
  30. vs := make([]*uint16, len(args))
  31. for i := range vs {
  32. vs[i] = syscall.StringToUTF16Ptr(args[i])
  33. }
  34. p = &vs[0]
  35. }
  36. return windows.StartService(s.Handle, uint32(len(args)), p)
  37. }
  38. // Control sends state change request c to the servce s.
  39. func (s *Service) Control(c svc.Cmd) (svc.Status, error) {
  40. var t windows.SERVICE_STATUS
  41. err := windows.ControlService(s.Handle, uint32(c), &t)
  42. if err != nil {
  43. return svc.Status{}, err
  44. }
  45. return svc.Status{
  46. State: svc.State(t.CurrentState),
  47. Accepts: svc.Accepted(t.ControlsAccepted),
  48. }, nil
  49. }
  50. // Query returns current status of service s.
  51. func (s *Service) Query() (svc.Status, error) {
  52. var t windows.SERVICE_STATUS
  53. err := windows.QueryServiceStatus(s.Handle, &t)
  54. if err != nil {
  55. return svc.Status{}, err
  56. }
  57. return svc.Status{
  58. State: svc.State(t.CurrentState),
  59. Accepts: svc.Accepted(t.ControlsAccepted),
  60. }, nil
  61. }