summaryrefslogtreecommitdiff
path: root/proc.go
blob: d78fbcf2fdb81162d05986c081d59555ba26b8f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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)
}
*/