Created
January 15, 2024 02:12
-
-
Save xieyuschen/21ba9de507f6c8c7e88b9a9f76112a53 to your computer and use it in GitHub Desktop.
Print All Processes with A Tree format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"github.com/mitchellh/go-ps" | |
"io" | |
"os" | |
) | |
func main() { | |
printProcessTree() | |
} | |
func printProcessTree() { | |
var w bytes.Buffer | |
entry := []int{1} | |
printLayer(New(), entry, &w, 0) | |
w.WriteTo(os.Stdout) | |
} | |
type Processes struct { | |
descents map[int][]int // ppid -> []pid | |
executable map[int]string // pid -> executable string | |
} | |
func New() *Processes { | |
pros, _ := ps.Processes() | |
m := make(map[int][]int) // ppid -> []pid | |
processM := make(map[int]string) // pid -> string | |
for _, p := range pros { | |
processM[p.Pid()] = p.Executable() | |
v, ok := m[p.PPid()] | |
if !ok { | |
m[p.PPid()] = []int{p.Pid()} | |
continue | |
} | |
m[p.PPid()] = append(v, p.Pid()) | |
} | |
return &Processes{ | |
descents: m, | |
executable: processM, | |
} | |
} | |
func printLayer(p *Processes, entry []int, w io.Writer, ident int) { | |
for _, e := range entry { | |
strLine := fmt.Sprintf("%s%d: %s\n", printIndent(ident), e, p.executable[e]) | |
w.Write([]byte(strLine)) | |
list, ok := p.descents[e] | |
if !ok { | |
continue | |
} | |
printLayer(p, list, w, ident+1) | |
} | |
} | |
func printIndent(number int) string { | |
var idents string | |
for i := 0; i < number-1; i++ { | |
idents += "\t" | |
} | |
idents += "|_______" | |
return idents | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output is: