[PATCH v2 1/3] perf sched stats: Fix SIGCHLD race in schedstat_record()

From: Swapnil Sapkal

Date: Thu Apr 09 2026 - 12:27:04 EST


When a very short-lived workload is used with 'perf sched stats record',
the child process can exit and deliver SIGCHLD between
evlist__start_workload() and pause(). Since pause() only returns when a
signal is received while suspended, and the SIGCHLD has already been
delivered and handled by then, pause() blocks indefinitely.

Fix this by blocking SIGCHLD, SIGINT and SIGTERM after
evlist__prepare_workload() (so the forked child does not inherit a
modified signal mask) and replacing pause() with sigsuspend().
sigsuspend() atomically restores the original mask and suspends the
process, ensuring no signal is lost regardless of how quickly the child
exits or the user sends Ctrl+C.

Reviewed-by: James Clark <james.clark@xxxxxxxxxx>
Assisted-by: Claude:claude-opus-4.6
Signed-off-by: Swapnil Sapkal <swapnil.sapkal@xxxxxxx>
---
tools/perf/builtin-sched.c | 19 +++++++++++++++++--
1 file changed, 17 insertions(+), 2 deletions(-)

diff --git a/tools/perf/builtin-sched.c b/tools/perf/builtin-sched.c
index 3f509cfdd58c..3f448acd5046 100644
--- a/tools/perf/builtin-sched.c
+++ b/tools/perf/builtin-sched.c
@@ -3807,6 +3807,7 @@ const char *output_name;
static int perf_sched__schedstat_record(struct perf_sched *sched,
int argc, const char **argv)
{
+ sigset_t sig_mask, oldmask;
struct perf_session *session;
struct target target = {};
struct evlist *evlist;
@@ -3899,11 +3900,25 @@ static int perf_sched__schedstat_record(struct perf_sched *sched,
if (err < 0)
goto out;

+ /*
+ * Block all handled signals so that a short-lived workload exiting
+ * (SIGCHLD) or an early Ctrl+C (SIGINT/SIGTERM) during the remaining
+ * setup cannot be delivered before we are ready to wait. sigsuspend()
+ * below will atomically unblock them. This is done after
+ * evlist__prepare_workload() so the forked child does not inherit a
+ * modified signal mask.
+ */
+ sigemptyset(&sig_mask);
+ sigaddset(&sig_mask, SIGCHLD);
+ sigaddset(&sig_mask, SIGINT);
+ sigaddset(&sig_mask, SIGTERM);
+ sigprocmask(SIG_BLOCK, &sig_mask, &oldmask);
+
if (argc)
evlist__start_workload(evlist);

- /* wait for signal */
- pause();
+ sigsuspend(&oldmask);
+ sigprocmask(SIG_SETMASK, &oldmask, NULL);

if (reset) {
err = disable_sched_schedstat();
--
2.43.0