Created
July 26, 2024 12:43
-
-
Save mamodev/e486e1c4fe91fcd570096ac3b904abd1 to your computer and use it in GitHub Desktop.
Golang PGrep
This file contains 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
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