github.com/juelite/golang.org-x-sys@v0.0.0-20181121071242-7b69e1c5db33/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  
    12  	"golang.org/x/sys/windows"
    13  	"golang.org/x/sys/windows/svc"
    14  )
    15  
    16  // TODO(brainman): Use EnumDependentServices to enumerate dependent services.
    17  
    18  // TODO(brainman): Use EnumServicesStatus to enumerate services in the specified service control manager database.
    19  
    20  // Service is used to access Windows service.
    21  type Service struct {
    22  	Name   string
    23  	Handle windows.Handle
    24  }
    25  
    26  // Delete marks service s for deletion from the service control manager database.
    27  func (s *Service) Delete() error {
    28  	return windows.DeleteService(s.Handle)
    29  }
    30  
    31  // Close relinquish access to the service s.
    32  func (s *Service) Close() error {
    33  	return windows.CloseServiceHandle(s.Handle)
    34  }
    35  
    36  // Start starts service s.
    37  // args will be passed to svc.Handler.Execute.
    38  func (s *Service) Start(args ...string) error {
    39  	var p **uint16
    40  	if len(args) > 0 {
    41  		vs := make([]*uint16, len(args))
    42  		for i, _ := range vs {
    43  			vs[i] = syscall.StringToUTF16Ptr(args[i])
    44  		}
    45  		p = &vs[0]
    46  	}
    47  	return windows.StartService(s.Handle, uint32(len(args)), p)
    48  }
    49  
    50  // Control sends state change request c to the servce s.
    51  func (s *Service) Control(c svc.Cmd) (svc.Status, error) {
    52  	var t windows.SERVICE_STATUS
    53  	err := windows.ControlService(s.Handle, uint32(c), &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  }
    62  
    63  // Query returns current status of service s.
    64  func (s *Service) Query() (svc.Status, error) {
    65  	var t windows.SERVICE_STATUS
    66  	err := windows.QueryServiceStatus(s.Handle, &t)
    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  	}, nil
    74  }