shell/proc.go

58 lines
977 B
Go
Raw Permalink Normal View History

package shell
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
// get your parent PID
func GetPPID(pid int) (int, error) {
data, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
if err != nil {
return 0, err
}
parts := strings.Fields(string(data))
if len(parts) < 4 {
return 0, fmt.Errorf("unexpected format of /proc/%d/stat", pid)
}
ppid, err := strconv.Atoi(parts[3])
if err != nil {
return 0, err
}
return ppid, nil
}
// get comm from proc
func GetComm(pid int) (string, error) {
data, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/comm", pid))
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
/*
func main() {
pid := os.Getpid()
ppid, err := getPPID(pid)
if err != nil {
fmt.Println("Error getting PPID:", err)
return
}
comm, err := getComm(ppid)
if err != nil {
fmt.Println("Error getting comm:", err)
return
}
fmt.Println(comm)
}
*/