[UMU learn golang](7) Set process exit code

conventional plan

Use os.Exit(exit_code) directly, but this is too violent, we need to pretend a little bit, so we found this: https://stackoverflow.com/questions/24601516/correct-way-to-set-exit-code -of-process

package main

import (
    "fmt"
    "os"
)

func main() {
    code := 0
    defer func() {
        os.Exit(code)
    }()
    defer func() {
        fmt.Println("Another deferred func")
    }()
    fmt.Println("Hello, 世界")
    code = 1
}

question

When you call panic, you know that the above methods are insufficient! After the panic, it will cause the main to exit. The Trace Log should be printed immediately, but when the main exits, os.Exit() is called, and then there is no more...

Sure enough, the force was hacked by lightning . Originally, when panic, the exit code should be 2. As a result, due to the effect of the above force code, the exit code became 0! If panic is called by itself, it can be changed and used in other ways; if it is other library functions, it is difficult to do...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325261542&siteId=291194637