1
0

daemon.go 2.2 KB

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