NOGU.D

どっかの大学の学部生のメモ程度の記事

Golang プログラムを終了

os.Exit()

os.Exitを使うとdeferは実行されない。


package main

import (
    "fmt"
    "os"
)

func main() {

    fmt.Println("!")

    os.Exit(3)
}
func Exit(code int) Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.

ドキュメントにはdeferに登録した関数をすべて破棄すると書かれている。

main関数でdefer文と併用してos#Exit関数を実行すると意図しない挙動をする可能性がある。また、「immediately」なので他のゴルーチンの終了などは待機しない。


$ go build main.go
$ ./main
$ echo $?
3
バイナリをビルドしてから実行する場合は、ターミナル上でステータスを確認することが可能。

参考