Skip to content

Instantly share code, notes, and snippets.

@xieyuschen
Created January 15, 2024 02:12
Show Gist options
  • Save xieyuschen/21ba9de507f6c8c7e88b9a9f76112a53 to your computer and use it in GitHub Desktop.
Save xieyuschen/21ba9de507f6c8c7e88b9a9f76112a53 to your computer and use it in GitHub Desktop.
Print All Processes with A Tree format
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
}
@xieyuschen
Copy link
Author

The output is:

e33cac2271af3358e2cd12c927e989c1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment