mirror of
https://github.com/DominicBreuker/pspy.git
synced 2025-12-21 03:34:50 +00:00
Added --ppid command line option that includes the parent process identifier.
Also included small refactoring in PSScanner module to allow for parameter to be passed.
This commit is contained in:
@@ -6,26 +6,19 @@ import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var procDirReader = func() ([]os.FileInfo, error) {
|
||||
return ioutil.ReadDir("/proc")
|
||||
}
|
||||
|
||||
var procStatusReader = func(pid int) ([]byte, error) {
|
||||
statPath := fmt.Sprintf("/proc/%d/status", pid)
|
||||
return ioutil.ReadFile(statPath)
|
||||
type procList map[int]struct{}
|
||||
|
||||
type pidProcessor interface {
|
||||
processNewPid(pid int)
|
||||
}
|
||||
|
||||
var cmdLineReader = func(pid int) ([]byte, error) {
|
||||
cmdPath := fmt.Sprintf("/proc/%d/cmdline", pid)
|
||||
return ioutil.ReadFile(cmdPath)
|
||||
}
|
||||
|
||||
type procList map[int]string
|
||||
|
||||
func (pl procList) refresh(eventCh chan PSEvent) error {
|
||||
func (pl procList) refresh(p pidProcessor) error {
|
||||
pids, err := getPIDs()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -35,7 +28,8 @@ func (pl procList) refresh(eventCh chan PSEvent) error {
|
||||
pid := pids[i]
|
||||
_, ok := pl[pid]
|
||||
if !ok {
|
||||
pl.addPid(pid, eventCh)
|
||||
p.processNewPid(pid)
|
||||
pl[pid] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,53 +67,3 @@ func file2Pid(f os.FileInfo) (int, error) {
|
||||
|
||||
return pid, nil
|
||||
}
|
||||
|
||||
func (pl procList) addPid(pid int, eventCh chan PSEvent) {
|
||||
cmd, err := getCmd(pid)
|
||||
if err != nil {
|
||||
cmd = "???" // process probably terminated
|
||||
}
|
||||
uid, err := getUID(pid)
|
||||
if err != nil {
|
||||
uid = -1
|
||||
}
|
||||
eventCh <- PSEvent{UID: uid, PID: pid, CMD: cmd}
|
||||
pl[pid] = cmd
|
||||
}
|
||||
|
||||
func getCmd(pid int) (string, error) {
|
||||
cmd, err := cmdLineReader(pid)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for i := 0; i < len(cmd); i++ {
|
||||
if cmd[i] == 0 {
|
||||
cmd[i] = 32
|
||||
}
|
||||
}
|
||||
return string(cmd), nil
|
||||
}
|
||||
|
||||
func getUID(pid int) (int, error) {
|
||||
stat, err := procStatusReader(pid)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
lines := strings.Split(string(stat), "\n")
|
||||
if len(lines) < 9 {
|
||||
return -1, fmt.Errorf("no uid information")
|
||||
}
|
||||
|
||||
uidL := strings.Split(lines[8], "\t")
|
||||
if len(uidL) < 2 {
|
||||
return -1, fmt.Errorf("uid line read incomplete")
|
||||
}
|
||||
|
||||
uid, err := strconv.Atoi(uidL[1])
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("converting %s to int: %v", uidL[1], err)
|
||||
}
|
||||
|
||||
return uid, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user