我需要defer使用C庫來釋放手動創建的分配,但我也需要os.Exit在某些時候使用非 0 狀態。棘手的部分是os.Exit跳過任何延遲指令:package mainimport "fmt"import "os"func main() { // `defer`s will _not_ be run when using `os.Exit`, so // this `fmt.Println` will never be called. defer fmt.Println("!") // sometimes ones might use defer to do critical operations // like close a database, remove a lock or free memory // Exit with status code. os.Exit(3)}游樂場:http : //play.golang.org/p/CDiAh9SXRM從https://gobyexample.com/exit竊取那么如何退出一個遵循聲明defer調用的 go 程序呢?有什么替代方法os.Exit嗎?
3 回答

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
只需將您的程序向下移動一個級別并返回您的退出代碼:
package main
import "fmt"
import "os"
func doTheStuff() int {
defer fmt.Println("!")
return 3
}
func main() {
os.Exit(doTheStuff())
}

白衣染霜花
TA貢獻1796條經驗 獲得超10個贊
runtime.Goexit()
是實現這一目標的簡單方法。
Goexit 終止調用它的 goroutine。沒有其他 goroutine 受到影響。Goexit 在終止 goroutine 之前運行所有延遲調用。然而,因為 Goexit 并不恐慌,這些延遲函數中的任何恢復調用都將返回 nil。
然而:
從主協程調用 Goexit 會終止該協程,而不會返回 func main。由于 func main 沒有返回,程序繼續執行其他 goroutine。如果所有其他 goroutine 退出,程序就會崩潰。
所以如果你從主 goroutine 調用它,main
你需要在頂部添加
defer os.Exit(0)
在此之下,您可能想要添加一些其他defer
語句,以通知其他 goroutine 停止和清理。
- 3 回答
- 0 關注
- 199 瀏覽
添加回答
舉報
0/150
提交
取消