Skip to content

Commit 9cd364a

Browse files
authored
send SIGINT and SIGTERM to children when received (#97)
1 parent 6b0fa55 commit 9cd364a

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

cmd/metrics/metrics.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,8 @@ func runCmd(cmd *cobra.Command, args []string) error {
504504
sig := <-sigChannel
505505
setSignalReceived()
506506
slog.Info("received signal", slog.String("signal", sig.String()))
507+
// propogate signal to children
508+
util.SignalChildren(sig)
507509
}()
508510
// round up to next perfPrintInterval second (the collection interval used by perf stat)
509511
if flagDuration != 0 {

internal/util/util.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ import (
1414
"fmt"
1515
"io"
1616
"io/fs"
17+
"log/slog"
1718
"math"
1819
"os"
20+
"os/exec"
1921
"os/user"
2022
"path/filepath"
2123
"regexp"
@@ -403,3 +405,35 @@ func GetAppDir() string {
403405
exePath, _ := os.Executable()
404406
return filepath.Dir(exePath)
405407
}
408+
409+
// SignalChildren sends a signal to all children of this process
410+
func SignalChildren(sig os.Signal) {
411+
// get list of child processes
412+
cmd := exec.Command("pgrep", "-P", strconv.Itoa(os.Getpid()))
413+
out, err := cmd.Output()
414+
if err != nil {
415+
slog.Error("failed to get child processes", slog.String("error", err.Error()))
416+
return
417+
}
418+
// send signal to each child
419+
for _, pid := range strings.Split(string(out), "\n") {
420+
if pid == "" {
421+
continue
422+
}
423+
pidInt, err := strconv.Atoi(pid)
424+
if err != nil {
425+
slog.Error("failed to convert pid to int", slog.String("pid", pid), slog.String("error", err.Error()))
426+
continue
427+
}
428+
proc, err := os.FindProcess(pidInt)
429+
if err != nil {
430+
slog.Error("failed to find process", slog.Int("pid", pidInt), slog.String("error", err.Error()))
431+
continue
432+
}
433+
slog.Info("sending signal to child process", slog.Int("pid", pidInt), slog.String("signal", sig.String()))
434+
err = proc.Signal(sig)
435+
if err != nil {
436+
slog.Error("failed to send signal to process", slog.Int("pid", pidInt), slog.String("error", err.Error()))
437+
}
438+
}
439+
}

0 commit comments

Comments
 (0)