From 9b6f7e82fd60ec9f51683bd0df6f44a887e25bc5 Mon Sep 17 00:00:00 2001
From: decanus <7621705+decanus@users.noreply.github.com>
Date: Thu, 16 Feb 2023 16:44:14 +0100
Subject: [PATCH] implemented OnKillRun

---
 command.go | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/command.go b/command.go
index b6e3f4a1..ed840bd2 100644
--- a/command.go
+++ b/command.go
@@ -23,9 +23,11 @@ import (
 	"fmt"
 	"io"
 	"os"
+	"os/signal"
 	"path/filepath"
 	"sort"
 	"strings"
+	"syscall"
 
 	flag "github.com/spf13/pflag"
 )
@@ -136,6 +138,8 @@ type Command struct {
 	PersistentPostRun func(cmd *Command, args []string)
 	// PersistentPostRunE: PersistentPostRun but returns an error.
 	PersistentPostRunE func(cmd *Command, args []string) error
+	// OnKillRun: run if a commands execution is exited
+	OnKillRun func(cmd *Command, args []string)
 
 	// groups for subcommands
 	commandgroups []*Group
@@ -906,6 +910,23 @@ func (c *Command) execute(a []string) (err error) {
 		argWoFlags = a
 	}
 
+	if c.OnKillRun != nil {
+		sigchan := make(chan os.Signal)
+		signal.Notify(
+			sigchan,
+			syscall.SIGINT,
+			syscall.SIGKILL,
+			syscall.SIGTERM,
+			syscall.SIGQUIT,
+		)
+
+		go func() {
+			_ = <-sigchan
+
+			c.OnKillRun(c, argWoFlags)
+		}()
+	}
+
 	if err := c.ValidateArgs(argWoFlags); err != nil {
 		return err
 	}