service.go 1.9 KB

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