Skip to content

how about a shutdown-hook? #5

Open

Description

@yingzhuo

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)
}

Activity

  1. yingzhuo commented on Dec 9, 2019

    @yingzhuo
    ContributorAuthor

    see here pls.

  2. subchen commented on Dec 9, 2019

    @subchen
    Owner

    Good point, let me port it from your fork.

  3. yingzhuo commented on Dec 9, 2019

    @yingzhuo
    ContributorAuthor

    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)
    	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions