From e38032ba2fce38ef6f9d0bab17296253425a055f Mon Sep 17 00:00:00 2001 From: jholdstock Date: Fri, 8 Sep 2023 11:17:16 +0100 Subject: [PATCH] vspd: Run deferred tasks on os.Exit. Any tasks deferred in the main func will not execute if os.Exit is called. Moving application logic down into a new func which is called by main works around this limitation. --- cmd/vspd/main.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/cmd/vspd/main.go b/cmd/vspd/main.go index 0993e90..855c7a9 100644 --- a/cmd/vspd/main.go +++ b/cmd/vspd/main.go @@ -10,19 +10,24 @@ import ( ) func main() { + os.Exit(run()) +} + +// run is the real main function for vspd. It is necessary to work around the +// fact that deferred functions do not run when os.Exit() is called. +func run() int { // Load config file and parse CLI args. cfg, err := loadConfig() if err != nil { fmt.Fprintf(os.Stderr, "loadConfig error: %v\n", err) - os.Exit(1) + return 1 } vspd, err := newVspd(cfg) if err != nil { fmt.Fprintf(os.Stderr, "newVspd error: %v\n", err) - os.Exit(1) + return 1 } - // Run until an exit code is returned. - os.Exit(vspd.run()) + return vspd.run() }