os.Exit will exit, and
defer updateCancel()
will not run101 // run command
102 if err := rootCmd.Execute(); err != nil {
103 fmt.Println(err)
104 os.Exit(1)105 }
106
107 updateCancel() // if the update checker hasn't completed by now, abort it
Description
Calls to os.Exit
or log.Fatal
and friends made in function with defer
statements do not execute those statements if control reaches the
os.Exit
or log.Fatal
and friends.
If the os.Exit
function happens in a goroutine, all the goroutines (including
the main one) will terminate immediately without executing any deferred statement.
Internally, log.Fatal
and friends (log.Fatalln
and log.Fatalf
) internally
uses os.Exit(1)
, which results in the immediate termination of the program
without executing the deferred statements.
It is recommended to handle such cases gracefully so that deferred statements are executed to necessary operations such as closing open file descriptors, cleanup, etc.
Bad practice
defer os.Remove(filename)
if bad {
log.Fatalf("something bad happened")
}
Recommended
defer os.Remove(filename)
if bad {
log.Printf("something bad happened")
return // exits with "exit status 0"
}
retcode := 0
defer func() { os.Exit(retcode) }
defer os.Remove(filename)
if bad {
log.Printf("something bad happened")
retcode = 1
return // exits with "exit status 1" because of topmost `defer` call
}