Last active
October 11, 2021 07:17
-
-
Save chidiwilliams/fa15c69b28785cab2639dec85981130f to your computer and use it in GitHub Desktop.
Print process tree
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 ( | |
"fmt" | |
"strings" | |
) | |
type Node struct { | |
Name string | |
Children []Node | |
} | |
func getTree(node Node) string { | |
return getBranch(node, "") | |
} | |
func getBranch(node Node, prefix string) string { | |
branch := node.Name | |
for i := 0; i < len(node.Children); i++ { | |
currPrefix := prefix + strings.Repeat(" ", len(node.Name)+1) | |
// add extra space for non-root nodes | |
if prefix != "" { | |
currPrefix += " " | |
} | |
var marker string | |
var childPrefix string | |
if i < len(node.Children)-1 { | |
marker = "|" | |
childPrefix = "|" | |
} else { | |
marker = "`" | |
childPrefix = " " // last child doesn't add its prefix | |
} | |
if len(node.Children) == 1 { | |
branch += "---" | |
} else if i == 0 { | |
branch += "-+-" | |
} else { | |
branch += "\n" + currPrefix + marker + "-" | |
} | |
// attach child branch | |
branch += getBranch(node.Children[i], currPrefix+childPrefix) | |
} | |
return branch | |
} | |
func main() { | |
node := Node{ | |
Name: "init", | |
Children: []Node{ | |
{Name: "amd"}, | |
{ | |
Name: "gnome-terminal", | |
Children: []Node{ | |
{ | |
Name: "bash", | |
Children: []Node{{Name: "vim"}}, | |
}, | |
{Name: "bash"}, | |
{ | |
Name: "bash", | |
Children: []Node{{Name: "pstree"}}, | |
}, | |
{ | |
Name: "bash", | |
Children: []Node{{Name: "ssh"}}, | |
}, | |
}, | |
}, | |
{ | |
Name: "gdm", | |
Children: []Node{ | |
{ | |
Name: "gdm", | |
Children: []Node{ | |
{Name: "X"}, | |
{ | |
Name: "gnome-session", | |
Children: []Node{ | |
{ | |
Name: "Gnome", | |
Children: []Node{ | |
{Name: "gnome-extra"}, | |
{Name: "gnome-extra-2"}, | |
}, | |
}, | |
{Name: "ssh-agent"}, | |
{Name: "true"}, | |
}, | |
}, | |
}, | |
}, | |
}, | |
}, | |
{Name: "atd"}, | |
}, | |
} | |
fmt.Println(getTree(node)) | |
} | |
/** | |
Output: | |
init-+-amd | |
|-gnome-terminal-+-bash---vim | |
| |-bash | |
| |-bash---pstree | |
| `-bash---ssh | |
|-gdm---gdm-+-X | |
| `-gnome-session-+-Gnome-+-gnome-extra | |
| | `-gnome-extra-2 | |
| |-ssh-agent | |
| `-true | |
`-atd | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Btw, here
bash is the parent of pstree, and bash is the parent of ssh. So you shouldn't build the node with this ->
{Name: "bash---pstree"}
.Like your approach!