Handle process signals through cooperative cancellation
This commit is contained in:
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/cli"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
@@ -11,11 +13,32 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
func run() int {
|
||||
app, err := cli.NewApplication(buildinfo.Version(), cli.Options{})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
return 1
|
||||
}
|
||||
ctx, stop := interruptContext()
|
||||
defer stop()
|
||||
outcome := app.Execute(ctx, os.Args[1:], commandkit.Streams{Out: os.Stdout, Err: os.Stderr})
|
||||
return outcome.Status
|
||||
}
|
||||
|
||||
func interruptContext() (context.Context, func()) {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
// Restore ordinary signal handling while cooperative cleanup runs.
|
||||
stop()
|
||||
close(done)
|
||||
}()
|
||||
return ctx, func() {
|
||||
stop()
|
||||
<-done
|
||||
}
|
||||
outcome := app.Execute(context.Background(), os.Args[1:], commandkit.Streams{Out: os.Stdout, Err: os.Stderr})
|
||||
os.Exit(outcome.Status)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user