Skip to content

Commit

Permalink
send SIGINT and SIGTERM to children when received (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
harp-intel authored Nov 20, 2024
1 parent 6b0fa55 commit 9cd364a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions cmd/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,8 @@ func runCmd(cmd *cobra.Command, args []string) error {
sig := <-sigChannel
setSignalReceived()
slog.Info("received signal", slog.String("signal", sig.String()))
// propogate signal to children
util.SignalChildren(sig)
}()
// round up to next perfPrintInterval second (the collection interval used by perf stat)
if flagDuration != 0 {
Expand Down
34 changes: 34 additions & 0 deletions internal/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import (
"fmt"
"io"
"io/fs"
"log/slog"
"math"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -403,3 +405,35 @@ func GetAppDir() string {
exePath, _ := os.Executable()
return filepath.Dir(exePath)
}

// SignalChildren sends a signal to all children of this process
func SignalChildren(sig os.Signal) {
// get list of child processes
cmd := exec.Command("pgrep", "-P", strconv.Itoa(os.Getpid()))
out, err := cmd.Output()
if err != nil {
slog.Error("failed to get child processes", slog.String("error", err.Error()))
return
}
// send signal to each child
for _, pid := range strings.Split(string(out), "\n") {
if pid == "" {
continue
}
pidInt, err := strconv.Atoi(pid)
if err != nil {
slog.Error("failed to convert pid to int", slog.String("pid", pid), slog.String("error", err.Error()))
continue
}
proc, err := os.FindProcess(pidInt)
if err != nil {
slog.Error("failed to find process", slog.Int("pid", pidInt), slog.String("error", err.Error()))
continue
}
slog.Info("sending signal to child process", slog.Int("pid", pidInt), slog.String("signal", sig.String()))
err = proc.Signal(sig)
if err != nil {
slog.Error("failed to send signal to process", slog.Int("pid", pidInt), slog.String("error", err.Error()))
}
}
}

0 comments on commit 9cd364a

Please sign in to comment.