google / subcommands

Go subcommand library.
Apache License 2.0
749 stars 48 forks source link

Cancel propagate on Signals #34

Closed xmlking closed 2 years ago

xmlking commented 3 years ago

is this the recommended way to propagate SIGTERM type of signals to downstream components via context? or are there any other techniques? https://github.com/billchen1977/fuchsia/blob/master/tools/integration/cmd/fint/main.go#L41

slewiskelly commented 3 years ago

Yes, this is a fine way of handling them.

There's no real need to include go.fuchsia.dev/fuchsia/tools/lib/command as a dependency, you could copy the function body into your own tool. So for SIGINT and SIGTERM specifically:

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    ch := make(chan os.Signal, 1)
    signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        defer signal.Stop(ch)
        select {
        case <-ctx.Done():
            return
        case <-ch:
            cancel()
        }
    }()

    os.Exit(int(subcommands.Execute(ctx)))
}
cristaloleg commented 2 years ago

Since Go 1.16 we've os/signal.NotifyContext https://pkg.go.dev/os/signal#NotifyContext