Open dodona2 opened 8 years ago
+1 would be nice to include this in the README
I'm new to golang and this really helped.
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
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) }
}