From bdcac675dc3ea0cf6be9ee5fd30811eb9c955be7 Mon Sep 17 00:00:00 2001 From: Slancaster1 Date: Wed, 28 Aug 2024 12:07:29 -0400 Subject: [PATCH] utils_sys.py: Add function for finding process PIDS Added small utility function get_pids_for(). This function reads the output of 'ps aux' and gets the pids for any process in . Signed-off-by: Slancaster1 --- virttest/utils_sys.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/virttest/utils_sys.py b/virttest/utils_sys.py index 7ce2584e37..bea2e9efc6 100644 --- a/virttest/utils_sys.py +++ b/virttest/utils_sys.py @@ -72,3 +72,33 @@ def get_host_bridge_id(session=None): host_bridges = re.findall(hostbridge_regex, output) return host_bridges if host_bridges else [] + + +def get_pids_for(process_names, sort_pids=True, session=None): + """ + Given a list of names, retrieve the PIDs for + matching processes. Sort of equivalent + to: 'ps aux | grep name' + + :param process_names: List of process names to look for + """ + + status, ps_cmd = cmd_status_output("ps aux", shell=True, session=session) + if status != 0 or not ps_cmd: + return [] + + ps_output = ps_cmd.split("\n") + relevant_procs = [ + proc + for proc in ps_output + for wanted_name in process_names + if wanted_name in proc + ] + + relevant_procs = [line.split() for line in relevant_procs] + relevant_pids = [int(proc[1]) for proc in relevant_procs] + + if sort_pids: + relevant_pids.sort() + + return relevant_pids