Exit codes and goroutines

If the os.Exit function happens in a goroutine, all the goroutines (including the main one) will terminate immediately without executing any deferred call, as follows:

package main

import (
"fmt"
"os"
"time"
)

func main() {
go func() {
defer fmt.Println("go end (deferred)")
fmt.Println("go start")
os.Exit(1)
}()
fmt.Println("main end (deferred)")
fmt.Println("main start")
time.Sleep(time.Second)
fmt.Println("main end")
}

The full example is available at https://play.golang.org/p/JVEB5MTcEoa.

It is necessary for you to use os.Exit carefully because, since all the deferred operations will not be executed, this could lead to resource leaks or errors, such as not flushing a buffer and not writing all the content to a file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.103.183