有什么办法可以退出Go程序,但执行所有挂起的延迟语句吗?清除临时文件的最佳方法
我一直在使用延迟清理临时文件,但当程序被Ctrl + C或os.Exit中断时,延迟语句不会被执行。
退出该程序用Ctrl + C,二者foo.txt的和跳回到bar.txt之后遗留:
package main
import (
"fmt"
"io/ioutil"
"os"
"os/signal"
"syscall"
)
func main() {
ioutil.WriteFile("./foo.txt", []byte("foo"), 0644)
defer os.RemoveAll("./foo.txt")
go func() {
ioutil.WriteFile("./bar.txt", []byte("bar"), 0644)
defer os.RemoveAll("./bar.txt")
for {
// various long running things
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
go func() {
<-c
fmt.Println("Received OS interrupt - exiting.")
os.Exit(0)
}()
for {
// various long running things
}
}
不,但你可以重构你的代码,所以它可以优雅地关闭,然后推迟执行。我建议在main的顶部声明'c'并将它传递给go例程。在for循环中,你需要一个select语句来监听'c',如果你得到一个信号,就停止你正在做的事情并返回。然后你不需要使用'os.Exit'来杀死你的goroutines(因为你从来不应该这么做),你的程序可以正常返回,从而允许你的被攻击的os.RemoveAll进行清理。 – evanmcdonnal