daemon.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package lib
  2. import (
  3. "io/ioutil"
  4. "log"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. )
  11. func InitDaemon(f string) {
  12. if len(os.Args) < 2 {
  13. return
  14. }
  15. var args []string
  16. args = append(args, os.Args[0])
  17. if len(os.Args) >= 2 {
  18. args = append(args, os.Args[2:]...)
  19. }
  20. args = append(args, "-log=file")
  21. switch os.Args[1] {
  22. case "start":
  23. start(args, f)
  24. os.Exit(0)
  25. case "stop":
  26. stop(f, args[0])
  27. os.Exit(0)
  28. case "restart":
  29. stop(f, args[0])
  30. start(args, f)
  31. os.Exit(0)
  32. case "install":
  33. if f == "nps" {
  34. InstallNps()
  35. }
  36. os.Exit(0)
  37. case "status":
  38. if status(f) {
  39. log.Printf("%s is running", f)
  40. } else {
  41. log.Printf("%s is not running", f)
  42. }
  43. os.Exit(0)
  44. }
  45. }
  46. func status(f string) bool {
  47. var cmd *exec.Cmd
  48. b, err := ioutil.ReadFile(filepath.Join(GetPidPath(), f+".pid"))
  49. if err == nil {
  50. if !IsWindows() {
  51. cmd = exec.Command("/bin/sh", "-c", "ps -ax | awk '{ print $1 }' | grep "+string(b))
  52. } else {
  53. cmd = exec.Command("tasklist", )
  54. }
  55. out, _ := cmd.Output()
  56. if strings.Index(string(out), string(b)) > -1 {
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. func start(osArgs []string, f string) {
  63. if status(f) {
  64. log.Printf(" %s is running", f)
  65. return
  66. }
  67. cmd := exec.Command(osArgs[0], osArgs[1:]...)
  68. cmd.Start()
  69. if cmd.Process.Pid > 0 {
  70. log.Println("start ok , pid:", cmd.Process.Pid, "config path:", GetRunPath())
  71. d1 := []byte(strconv.Itoa(cmd.Process.Pid))
  72. ioutil.WriteFile(filepath.Join(GetPidPath(), f+".pid"), d1, 0600)
  73. } else {
  74. log.Println("start error")
  75. }
  76. }
  77. func stop(f string, p string) {
  78. if !status(f) {
  79. log.Printf(" %s is not running", f)
  80. return
  81. }
  82. var c *exec.Cmd
  83. var err error
  84. if IsWindows() {
  85. p := strings.Split(p, `\`)
  86. c = exec.Command("taskkill", "/F", "/IM", p[len(p)-1])
  87. } else {
  88. b, err := ioutil.ReadFile(filepath.Join(GetPidPath(), f+".pid"))
  89. if err == nil {
  90. c = exec.Command("/bin/bash", "-c", `kill -9 `+string(b))
  91. } else {
  92. log.Fatalln("stop error,PID file does not exist")
  93. }
  94. }
  95. err = c.Run()
  96. if err != nil {
  97. log.Println("stop error,", err)
  98. } else {
  99. log.Println("stop ok")
  100. }
  101. }