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