Skip to content

Instantly share code, notes, and snippets.

@mamodev
Created July 26, 2024 12:43
Show Gist options
  • Save mamodev/e486e1c4fe91fcd570096ac3b904abd1 to your computer and use it in GitHub Desktop.
Save mamodev/e486e1c4fe91fcd570096ac3b904abd1 to your computer and use it in GitHub Desktop.
Golang PGrep
func PGrep(serviceName string) []*os.Process {
process := make([]*os.Process, 0)
command := fmt.Sprintf("ps -eo pid,command | grep \"%s\" | grep -v grep", serviceName)
res, err := exec.Command("sh", "-c", command).Output()
if err != nil {
return nil
}
for _, line := range strings.Split(string(res), "\n") {
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}
pid, err := strconv.Atoi(parts[0])
if err != nil {
continue
}
proc, err := os.FindProcess(pid)
if err != nil {
continue
}
process = append(process, proc)
}
return process
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment