陷阱os.Exit在golang

时间:2016-09-15 11:02:31

标签: go

我可以在中断时运行一些清理(当我按 ctrl c 时)。

$ go build 
$ ./exit
^Creceived interrupt signal

是否有可能以相同的方式os.Exit调用并在程序退出之前运行一些代码?代码:

package main

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

func main() {
    handleInterrupt(2)
    time.Sleep(2 * time.Second)
    os.Exit(1) // how to trap it?
}
func handleInterrupt(intrptChSize int) {
    s := make(chan os.Signal, intrptChSize)
    signal.Notify(s,
        syscall.SIGABRT,
        syscall.SIGALRM,
        syscall.SIGBUS,
        syscall.SIGCHLD,
        syscall.SIGCONT,
        syscall.SIGEMT,
        syscall.SIGFPE,
        syscall.SIGHUP,
        syscall.SIGILL,
        syscall.SIGINFO,
        syscall.SIGINT,
        syscall.SIGIO,
        syscall.SIGIOT,
        syscall.SIGKILL,
        syscall.SIGPIPE,
        syscall.SIGPROF,
        syscall.SIGQUIT,
        syscall.SIGSEGV,
        syscall.SIGSTOP,
        syscall.SIGSYS,
        syscall.SIGTERM,
        syscall.SIGTRAP,
        syscall.SIGTSTP,
        syscall.SIGTTIN,
        syscall.SIGTTOU,
        syscall.SIGURG,
        syscall.SIGUSR1,
        syscall.SIGUSR2,
        syscall.SIGVTALRM,
        syscall.SIGWINCH,
        syscall.SIGXCPU,
        syscall.SIGXFSZ)
    go func() {
        for sig := range s {
            fmt.Printf("received %s signal\n", sig)
            //cleanup()
        }
    }()
}

我知道在此示例中,我可以在每个cleanup代码之前运行os.Exit()

cleanup()
os.Exit(1)

但在我的真实项目中,我正在导入无法编辑的代码。这段代码包含os.Exit次调用,我希望在程序退出之前进行一些清理,而不需要编辑导入的代码。

1 个答案:

答案 0 :(得分:4)

你做不到。来自TFM:

  

程序立即终止;延期函数不会运行。