     1	package main
     2	
     3	import (
     4		"os"
     5		"fmt"
     6		"sort"
     7		"bufio"
     8		"strings"
     9		"strconv"
    10		"container/vector"
    11	)
    12	
    13	const (
    14		PID = iota
    15		PPID
    16	)
    17	
    18	func atoi(s string) (x int) {
    19		x, _ = strconv.Atoi(s)
    20		return
    21	}
    22	
    23	func main() {
    24		pr, pw, _ := os.Pipe()
    25		defer pr.Close()
    26		r := bufio.NewReader(pr)
    27		w := bufio.NewWriter(os.Stdout)
    28		defer w.Flush()
    29		pid, _ := os.ForkExec("/bin/ps", []string{"ps", "-e", "-opid,ppid,comm"}, nil, "", []*os.File{nil, pw, nil})
    30		defer os.Wait(pid, os.WNOHANG)
    31		pw.Close()
    32	
    33		child := make(map[int]*vector.IntVector)
    34		s, ok := r.ReadString('\n') // Discard the header line
    35		s, ok = r.ReadString('\n')
    36		for ok == nil {
    37			f := strings.Fields(s)
    38			if _, present := child[atoi(f[PPID])]; !present {
    39				v := new(vector.IntVector)
    40				child[atoi(f[PPID])] = v
    41			}
    42			// Save the child PIDs on a vector
    43			child[atoi(f[PPID])].Push(atoi(f[PID]))
    44			s, ok = r.ReadString('\n')
    45		}
    46	
    47		// Sort the PPIDs
    48		schild := make([]int, len(child))
    49		i := 0
    50		for k, _ := range child {
    51			schild[i] = k
    52			i++
    53		}
    54		sort.SortInts(schild)
    55		// Walk throught the sorted list
    56		for _, ppid := range schild {
    57			fmt.Printf("Pid %d has %d child", ppid, child[ppid].Len())
    58			if child[ppid].Len() == 1 {
    59				fmt.Printf(": %v\n", []int(*child[ppid]))
    60			} else {
    61				fmt.Printf("ren: %v\n", []int(*child[ppid]))
    62			}
    63		}
    64	}
