You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

85 lines
2.0 KiB

  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. "strings"
  9. "time"
  10. "golang.org/x/sys/windows/svc"
  11. "golang.org/x/sys/windows/svc/debug"
  12. "golang.org/x/sys/windows/svc/eventlog"
  13. )
  14. var elog debug.Log
  15. type myservice struct{}
  16. func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
  17. const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
  18. changes <- svc.Status{State: svc.StartPending}
  19. fasttick := time.Tick(500 * time.Millisecond)
  20. slowtick := time.Tick(2 * time.Second)
  21. tick := fasttick
  22. changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
  23. elog.Info(1, strings.Join(args, "-"))
  24. loop:
  25. for {
  26. select {
  27. case <-tick:
  28. beep()
  29. elog.Info(1, "beep")
  30. case c := <-r:
  31. switch c.Cmd {
  32. case svc.Interrogate:
  33. changes <- c.CurrentStatus
  34. // Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4
  35. time.Sleep(100 * time.Millisecond)
  36. changes <- c.CurrentStatus
  37. case svc.Stop, svc.Shutdown:
  38. break loop
  39. case svc.Pause:
  40. changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
  41. tick = slowtick
  42. case svc.Continue:
  43. changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
  44. tick = fasttick
  45. default:
  46. elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
  47. }
  48. }
  49. }
  50. changes <- svc.Status{State: svc.StopPending}
  51. return
  52. }
  53. func runService(name string, isDebug bool) {
  54. var err error
  55. if isDebug {
  56. elog = debug.New(name)
  57. } else {
  58. elog, err = eventlog.Open(name)
  59. if err != nil {
  60. return
  61. }
  62. }
  63. defer elog.Close()
  64. elog.Info(1, fmt.Sprintf("starting %s service", name))
  65. run := svc.Run
  66. if isDebug {
  67. run = debug.Run
  68. }
  69. err = run(name, &myservice{})
  70. if err != nil {
  71. elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err))
  72. return
  73. }
  74. elog.Info(1, fmt.Sprintf("%s service stopped", name))
  75. }