mitchellh / go-ps

Find, list, and inspect processes from Go (golang).
https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc
MIT License
1.47k stars 251 forks source link

example code #8

Open dodona2 opened 8 years ago

dodona2 commented 8 years ago

Proposal:

// -- compile-command: "go build main.go" -- // https://golang.org/pkg/errors/#pkg-index package main

import ( "errors" "fmt" "os" "github.com/mitchellh/go-ps" "github.com/pborman/getopt" )

const ()

func PS(){ ps, := ps.Processes() fmt.Println(ps[0].Executable()) for pp, := range(ps){ fmt.Printf("%d %s\n", ps[pp].Pid(),ps[pp].Executable()) } }

func FindProcess(key string) (int, string, error) { pname := "" pid := 0 err := errors.New("not found") ps, := ps.Processes() for i, := range ps { if ps[i].Executable() == key { pid = ps[i].Pid() pname = ps[i].Executable() err = nil break } } return pid, pname, err } // FindProcess( key string ) ( int, string, error )

func main() { // exit code rc := 0 // values from command line optHelp := getopt.BoolLong("help", 0, "Help") getopt.Parse() if *optHelp { getopt.Usage() os.Exit(rc) } if pid, s, err := FindProcess("emacs"); err == nil { fmt.Printf ("Pid:%d, Pname:%s\n", pid, s) }

fmt.Println("")
os.Exit(rc)

}

pfeilbr commented 8 years ago

+1 would be nice to include this in the README

ahammond commented 6 years ago

I'm new to golang and this really helped.

stevenspiel commented 6 years ago

slightly refactored (very helpful btw):

main.go:

package main

import (
    "errors"
    "fmt"
    "os"
    "github.com/mitchellh/go-ps"
    "github.com/pborman/getopt"
)

func main() {
    // exit code
    rc := 0
    // values from command line
    optHelp := getopt.BoolLong("help", 0, "Help")
    getopt.Parse()

    if *optHelp {
        getopt.Usage()
        os.Exit(rc)
    }

    if pid, s, err := FindProcess("emacs"); err == nil {
        fmt.Printf ("Pid:%d, Pname:%s\n", pid, s)
    }

    fmt.Println("")
    os.Exit(rc)
}

func PS() {
    ps, _ := ps.Processes()
    fmt.Println(ps[0].Executable())

    for pp := range ps {
        fmt.Printf("%d %s\n", ps[pp].Pid(), ps[pp].Executable())
    }
}

// FindProcess( key string ) ( int, string, error )
func FindProcess(key string) (int, string, error) {
    pname := ""
    pid := 0
    err := errors.New("not found")
    ps, _ := ps.Processes()

    for i, _ := range ps {
        if ps[i].Executable() == key {
            pid = ps[i].Pid()
            pname = ps[i].Executable()
            err = nil
            break
        }
    }
    return pid, pname, err
}

execution:

$ go get github.com/mitchellh/go-ps
$ go get github.com/pborman/getopt
$ go build main.go