go-play / pp.go

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"os/exec"

	"sort"
	"strconv"
	"strings"
)

type IntVector []int

func (iv *IntVector) Len() int {
	return len(*iv)
}

func (iv *IntVector) Less(i, j int) bool {
	return (*iv)[i] < (*iv)[j]
}

func (iv *IntVector) Swap(i, j int) {
	(*iv)[i], (*iv)[j] = (*iv)[j], (*iv)[i]
}

func keys(m map[int]*IntVector) []int {
	keys := make([]int, len(m))
	i := 0
	for k, _ := range m {
		keys[i] = k
		i++
	}

	return keys
}

func main() {
	cmd := exec.Command("/bin/ps", "-e", "-opid,ppid")
	out, err := cmd.Output()
	if err != nil {
		log.Fatalf("error: can't run ps - %v\n", err)
	}

	reader := bytes.NewBuffer(out)
	ps := make(map[int]*IntVector)
	// Skip Header
	_, err = reader.ReadBytes('\n')
	if err != nil {
		log.Fatalf("can't read - %v\n", err)
	}

	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			if err != io.EOF {
				log.Fatalf("unknown error - %s", err)
			}
			break
		}

		fields := strings.Fields(line)
		parent_pid, _ := strconv.Atoi(fields[1])
		children := ps[parent_pid]

		if children == nil {
			children = new(IntVector)
			ps[parent_pid] = children
		}

		child_pid, _ := strconv.Atoi(fields[0])
		*children = append(*children, child_pid)
	}

	pids := keys(ps)
	sort.Ints(pids)
	for _, pid := range pids {
		children := ps[pid]
		sort.Sort(children)
		fmt.Printf("Pid %d had %d children: [", pid, children.Len())
		for i := 0; i < children.Len(); i++ {
			fmt.Printf("%d", (*children)[i])
			if i < (children.Len() - 1) {
				fmt.Printf(", ")
			}
		}
		fmt.Printf("]\n")
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.