[PATCH v5 07/13] perf stat: factor out event handling loop into dispatch_events()

Alexey Budankov
2020-06-01T15:56:38Z

Consolidate event dispatching loops for launch, attach and system wide
monitoring use cases into common dispatch_events() function. If passed
pid contains valid pid i.e. doesn't equal to -1 then the function returns
pid process exit status in case the process terminates during monitoring.

Signed-off-by: Alexey Budankov <alexey.budankov@linux.intel.com>
---
tools/perf/builtin-stat.c | 35 ++++++++++++++++++++++++-----------
1 file changed, 24 insertions(+), 11 deletions(-)

diff --git a/tools/perf/builtin-stat.c b/tools/perf/builtin-stat.c
index dc7506be8bbd..8eeaf92912d8 100644
--- a/tools/perf/builtin-stat.c
+++ b/tools/perf/builtin-stat.c
@@ -504,6 +504,27 @@ static bool is_target_alive(struct target *_target,
return false;
}

+static int dispatch_events(pid_t pid, bool timeout, int interval, int *times, struct timespec *ts)
+{
+ bool stop = false;
+ int child = 0, status = 0;
+
+ while (1) {
+ if (pid != -1)
+ child = waitpid(pid, &status, WNOHANG);
+ else
+ child = is_target_alive(&target, evsel_list->core.threads) == false ? 1 : 0;
+
+ if (done || stop || child)
+ break;
+
+ nanosleep(ts, NULL);
+ stop = process_timeout(timeout, interval, times);
+ }
+
+ return status;
+}
+
enum counter_recovery {
COUNTER_SKIP,
COUNTER_RETRY,
@@ -575,7 +596,6 @@ static int __run_perf_stat(int argc, const char **argv, int run_idx)
struct affinity affinity;
int i, cpu;
bool second_pass = false;
- bool stop = false;

if (interval) {
ts.tv_sec = interval / USEC_PER_MSEC;
@@ -744,12 +764,8 @@ static int __run_perf_stat(int argc, const char **argv, int run_idx)
perf_evlist__start_workload(evsel_list);
enable_counters();

- if (interval || timeout) {
- while (!stop && !waitpid(child_pid, &status, WNOHANG)) {
- nanosleep(&ts, NULL);
- stop = process_timeout(timeout, interval, &times);
- }
- }
+ if (interval || timeout)
+ status = dispatch_events(child_pid, timeout, interval, &times, &ts);
if (child_pid != -1) {
if (timeout)
kill(child_pid, SIGTERM);
@@ -766,10 +782,7 @@ static int __run_perf_stat(int argc, const char **argv, int run_idx)
psignal(WTERMSIG(status), argv[0]);
} else {
enable_counters();
- while (!done && !stop && is_target_alive(&target, evsel_list->core.threads)) {
- nanosleep(&ts, NULL);
- stop = process_timeout(timeout, interval, &times);
- }
+ dispatch_events(-1, timeout, interval, &times, &ts);
}

disable_counters();
--
2.24.1