Skip to content

Instantly share code, notes, and snippets.

@ggaaooppeenngg
Created October 2, 2014 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggaaooppeenngg/06c0a567a7c87ef916ed to your computer and use it in GitHub Desktop.
Save ggaaooppeenngg/06c0a567a7c87ef916ed to your computer and use it in GitHub Desktop.
守护进程
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"time"
)
var timeFormat = "2006-01-02 15:04:05"
var restartTimeLimit = 1000
func main() {
lf, err := os.OpenFile("log.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0600)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer lf.Close()
// log
l := log.New(lf, "", os.O_APPEND)
p, _ := filepath.Abs(os.Args[1])
for i := 0; i < restartTimeLimit; i++ {
cmd := exec.Command(p)
err := cmd.Start()
cmd.Stdout = os.Stdout
if err != nil {
l.Printf("%s process start error : %s", time.Now().Format(timeFormat), err.Error())
time.Sleep(time.Second * 5)
continue
}
l.Printf("%s process start", time.Now().Format(timeFormat))
err = cmd.Wait()
if err != nil {
l.Printf("%s process end error: %s", time.Now().Format(timeFormat), err.Error())
} else {
l.Printf("%s process end", time.Now().Format(timeFormat))
}
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment