15 Star 52 Fork 12

DiDi-opensource / sgt

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
watcher.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
Ulric Qin 提交于 2018-10-12 13:22 . push to github
package watcher
import (
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
)
type Watcher struct {
Pid int
Exe string
Dur time.Duration
Dev bool
}
func NewWatcher(exe string, dur time.Duration) *Watcher {
return &Watcher{
Exe: exe,
Dur: dur,
}
}
func (w *Watcher) Start(f func()) {
// clean deleted process
fs, err := ioutil.ReadDir("/proc")
if err != nil {
if w.Dev {
log.Println("ERR: cannot read /proc:", err)
}
return
}
sz := len(fs)
for i := 0; i < sz; i++ {
if !fs[i].IsDir() {
continue
}
name := fs[i].Name()
pid, err := strconv.Atoi(name)
if err != nil {
continue
}
exe := fmt.Sprintf("/proc/%d/exe", pid)
if !IsExist(exe) {
continue
}
target, err := os.Readlink(exe)
if err == nil && strings.Contains(target, w.Exe) && strings.Contains(target, "deleted") {
proc, err := os.FindProcess(pid)
if err != nil {
if w.Dev {
log.Printf("ERR: cannot find process[pid:%d]: %v", pid, err)
}
continue
}
err = proc.Kill()
if err != nil && w.Dev {
log.Printf("ERR: cannot kill process[pid:%d]: %v", pid, err)
}
}
}
for {
time.Sleep(w.Dur)
w.check(f)
}
}
func (w *Watcher) check(f func()) {
defer func() {
if err := recover(); err != nil {
if w.Dev {
log.Println("PANIC:", err)
}
return
}
}()
if w.Pid > 0 {
target, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", w.Pid))
if err == nil && target == w.Exe {
return
}
}
fs, err := ioutil.ReadDir("/proc")
if err != nil {
if w.Dev {
log.Println("ERR: cannot read /proc:", err)
}
return
}
sz := len(fs)
for i := 0; i < sz; i++ {
if !fs[i].IsDir() {
continue
}
name := fs[i].Name()
pid, err := strconv.Atoi(name)
if err != nil {
continue
}
exe := fmt.Sprintf("/proc/%d/exe", pid)
if !IsExist(exe) {
continue
}
target, err := os.Readlink(exe)
if err == nil && target == w.Exe {
w.Pid = pid
return
}
}
// w.Exe not found
f()
}
func IsExist(fp string) bool {
_, err := os.Stat(fp)
return err == nil || os.IsExist(err)
}
Go
1
https://gitee.com/didiopensource/sgt.git
git@gitee.com:didiopensource/sgt.git
didiopensource
sgt
sgt
3c772d0974fe

搜索帮助