Skip to content

Commit

Permalink
Run deferred tasks on os.Exit.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jholdstock committed Oct 12, 2023
1 parent acbea17 commit 20e8537
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions decred.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,18 @@ func (c *crawler) run(ctx context.Context) {
}

func main() {
os.Exit(run())
}

// run is the real main function for dcrseeder. It is necessary to work around
// the fact that deferred functions do not run when os.Exit() is called.
func run() int {
ctx := shutdownListener()

cfg, err := loadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "loadConfig: %v\n", err)
os.Exit(1)
return 1
}

// Prefix log lines with current network, e.g. "[mainnet]" or "[testnet]".
Expand All @@ -162,7 +168,7 @@ func main() {
amgr, err := NewManager(cfg.dataDir, log)
if err != nil {
fmt.Fprintf(os.Stderr, "NewManager: %v\n", err)
os.Exit(1)
return 1
}

amgr.AddAddresses([]netip.AddrPort{cfg.seederIP})
Expand All @@ -171,7 +177,8 @@ func main() {

server, err := newServer(cfg.Listen, amgr, log)
if err != nil {
log.Fatal(err)
fmt.Fprint(os.Stderr, err)
return 1
}

var wg sync.WaitGroup
Expand Down Expand Up @@ -200,4 +207,6 @@ func main() {
// Wait for crawler and http server, then stop address manager.
wg.Wait()
log.Print("Bye!")

return 0
}

0 comments on commit 20e8537

Please sign in to comment.