2
0

More than 1 year has passed since last update.

[Go] os.Exit()について

Last updated at Posted at 2023-07-24

os.Exit()とは?

os.Exit()とは、与えられたステータスコードを出力すると共に、プロセスを即時終了する関数です。
ステータスコードの慣習的には、

  • 0 = 成功
  • 0以外 = 失敗

のようで、ステータスコードの範囲は [0 ~ 125]が推奨されています。

実際に実行してみると、ステータスコード0以外の場合は、"exit status 1"とともにプログラムが終了します。

package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("hello world")
	os.Exit(1)
	fmt.Println("ops")
}

出力
$ go run ./main.go
hello world
exit status 1

deferファンクションは実行しない

os.Exit()はプロセスを即時終了させ、deferファンクションは実行しないようです。

package main

import (
	"fmt"
	"os"
)

func main() {
	defer fmt.Println("oops")
	fmt.Println("hello world")
	os.Exit(1)
}
出力.deferで指定していた"oops"が出力されない
$ go run ./main.go
hello world
exit status 1
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0