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.
 
 
 

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