go实现进程监控并启动

【go实现进程监控并启动】弓背霞明剑照霜,秋风走马出咸阳。这篇文章主要讲述go实现进程监控并启动相关的知识,希望能为你提供帮助。
一个简单的实现进程监控命令

package main import "fmt" import "strings" import "net/http" import "os/exec" import "time" func SendDingMsg(msg string) { //请求地址模板 webHook := `https://oapi.dingtalk.com/robot/send?access_token=xxxx` //填写钉钉token content := `{"msgtype": "text", "text": {"content": "`+ msg + `"} }` //创建一个请求 req, err := http.NewRequest("POST", webHook, strings.NewReader(content)) if err != nil { fmt.Println(err) }client := & http.Client{} //设置请求头 req.Header.Set("Content-Type", "application/json; charset=utf-8") //发送请求 resp, err := client.Do(req) //关闭请求 defer resp.Body.Close()if err != nil { // handle error fmt.Println(err) } }func runInLinux(cmd string) (string, error) { //fmt.Println("Running Linux cmd:" + cmd) result, err := exec.Command("/bin/sh", "-c", cmd).Output() if err != nil { return "", err } return strings.TrimSpace(string(result)), err } func CheckAllProRunning(){ cmd := `xxxx`检查命令 start := `xxxxx`启动命令 pid ,err := runInLinux(cmd) fmt.Println(pid,err) if pid == ""{ fmt.Println("进程不存在的!!!") SendDingMsg("项目:进程不存在的,已经开始重启") pid2,_ := runInLinux(start) if pid2 != ""{ fmt.Println("进程启动成功!!!") SendDingMsg("项目:已经重启成功!!!") } }} func MonitorAllProRunning(){ for{ CheckAllProRunning() time.Sleep(60 * time.Second) //定义多长时间检查一次 } } func main(){ defer func() { if err := recover(); err != nil { fmt.Println("程序异常!!!") } }() MonitorAllProRunning()}

打包并启动
go build checkprocess.go nohup ./checkprocess &


    推荐阅读