parent
6e3c782d75
commit
a6d578d154
@ -0,0 +1,81 @@
|
|||||||
|
package gops
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
sigar "github.com/cloudfoundry/gosigar"
|
||||||
|
mps "github.com/mitchellh/go-ps"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Process struct {
|
||||||
|
mps.Process
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProcess(pid int) (p Process, err error) {
|
||||||
|
mp, err := mps.FindProcess(pid)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return Process{
|
||||||
|
Process: mp,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Process) Mem() (m sigar.ProcMem, err error) {
|
||||||
|
err = m.Get(p.Pid())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProcInfo struct {
|
||||||
|
Pid int
|
||||||
|
Rss int
|
||||||
|
PCpu float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// CPU Percent * 100
|
||||||
|
// only linux and darwin works
|
||||||
|
func (p *Process) ProcInfo() (pi ProcInfo, err error) {
|
||||||
|
pi.Pid = p.Pid()
|
||||||
|
cmd := exec.Command("ps", "-o", "pcpu,rss", "-p", strconv.Itoa(p.Pid()))
|
||||||
|
output, err := cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
err = errors.New("ps err: " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fields := strings.SplitN(string(output), "\n", 2)
|
||||||
|
if len(fields) != 2 {
|
||||||
|
err = errors.New("parse ps command out format error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = fmt.Sscanf(fields[1], "%f %d", &pi.PCpu, &pi.Rss)
|
||||||
|
pi.Rss *= 1024
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all child process
|
||||||
|
func (p *Process) Children(recursive bool) (cps []Process) {
|
||||||
|
pses, err := mps.Processes()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pidMap := make(map[int][]mps.Process, 0)
|
||||||
|
for _, p := range pses {
|
||||||
|
pidMap[p.PPid()] = append(pidMap[p.PPid()], p)
|
||||||
|
}
|
||||||
|
var travel func(int)
|
||||||
|
travel = func(pid int) {
|
||||||
|
for _, p := range pidMap[pid] {
|
||||||
|
cps = append(cps, Process{p})
|
||||||
|
if recursive {
|
||||||
|
travel(p.Pid())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
travel(p.Pid())
|
||||||
|
return
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package gops
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestProcInfo(t *testing.T) {
|
||||||
|
p, err := NewProcess(6464)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pi, err := p.ProcInfo()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log(pi)
|
||||||
|
}
|
Loading…
Reference in new issue