Created
May 9, 2017 02:08
-
-
Save groob/88e81f88af652eadbe0f75e961e675da to your computer and use it in GitHub Desktop.
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 ( | |
"bufio" | |
"bytes" | |
"flag" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"os/exec" | |
"strconv" | |
"time" | |
) | |
func main() { | |
path := flag.String("b", "", "binary path") | |
flag.Parse() | |
cmd := exec.Command(*path) | |
if err := cmd.Start(); err != nil { | |
log.Fatal(err) | |
} | |
pid := cmd.Process.Pid | |
out, err := ps(pid) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer cmd.Process.Kill() | |
fmt.Println(string(out)) | |
knownPids := map[int]bool{} | |
for { | |
ints, _ := pgrep(pid) | |
for _, i := range ints { | |
if knownPids[i] { | |
continue | |
} | |
out, err := ps(i) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(string(out)) | |
knownPids[i] = true | |
} | |
time.Sleep(1 * time.Second) | |
} | |
time.Sleep(60 * time.Second) | |
} | |
func ps(pid int) ([]byte, error) { | |
out, err := exec.Command("ps", "-p", fmt.Sprintf("%d", pid)).CombinedOutput() | |
return out, err | |
} | |
func pgrep(pid int) ([]int, error) { | |
cmd := exec.Command("pgrep", "-P", fmt.Sprintf("%d", pid)) | |
cmd.Stderr = os.Stderr | |
out, err := cmd.Output() | |
if err != nil { | |
return nil, err | |
} | |
var ints []int | |
r := bufio.NewReader(bytes.NewReader(out)) | |
for { | |
line, _, err := r.ReadLine() | |
if err == io.EOF { | |
break | |
} | |
if err != nil { | |
return nil, err | |
} | |
if i, err := strconv.Atoi(string(line)); err == nil { | |
ints = append(ints, i) | |
} | |
} | |
return ints, err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment