subchen/go-cli

how about a shutdown-hook?

yingzhuo opened this issue · 3 comments

if we run app in docker container, when container stops, docker engine will send a signal (SIGTERM) (value: 15) to the process which pid equals 1.

how a about we add shutdown-hook to thego-cli. example:

app := cli.NewApp()
app.OnTerm = func (sigValue int) {
    fmt.Println("关闭文件")
}

here is a tip shows how golang handle signals:

package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
)

func main() {

	fmt.Println("pid is ", os.Getpid())

	sigs := make(chan os.Signal, 1)
	exit := make(chan bool, 1)

	signal.Notify(sigs, syscall.SIGTERM)

	go func() {
		select {
		case <-sigs:
			fmt.Println("关闭文件")
			exit <- true
		}
	}()

	select {
	case <-exit:
		break
	}

	close(sigs)
	close(exit)
}

see here pls.

Good point, let me port it from your fork.

Here is example to show how stop the app gracefully. :)

	app.OnAppTerminating = func(_ *cli.Context, signals chan os.Signal) {
		defer close(signals)

		if !cnf.QuietMode {
			fmt.Println("shutdown")
		}

		signal.Stop(signals)
		syscall.Kill(os.Getpid(), syscall.SIGTERM)
	}