Skip to content

Commit

Permalink
main: Correct defer handling in main entrypoint.
Browse files Browse the repository at this point in the history
This refactors the main code into a separate function that returns an
error instead of invoking os.Exit directly to ensure that the defers
that are setup prior to the exits are run as intended.

The main func will now exit with the non-zero error code when an error
is returned from the refactored separate func.
  • Loading branch information
davecgh authored and jholdstock committed Sep 12, 2023
1 parent ca751f2 commit 433a31b
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions dcrpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ func newPool(db pool.Database, cfg *config) (*miningPool, error) {
return p, nil
}

func main() {
// realMain is the real main function for dcrpool. It is necessary to work
// around the fact that deferred functions do not run when os.Exit() is called.
func realMain() error {
// Listen for interrupt signals.
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, signals...)
Expand All @@ -142,7 +144,7 @@ func main() {
// logging and configures it accordingly.
cfg, _, err := loadConfig()
if err != nil {
os.Exit(1)
return err
}
defer func() {
if logRotator != nil {
Expand All @@ -160,13 +162,13 @@ func main() {

if err != nil {
mpLog.Errorf("failed to initialize database: %v", err)
os.Exit(1)
return err
}

p, err := newPool(db, cfg)
if err != nil {
mpLog.Errorf("failed to initialize pool: %v", err)
os.Exit(1)
return err
}

if cfg.Profile != "" {
Expand Down Expand Up @@ -215,4 +217,12 @@ func main() {

db.Close()
mpLog.Info("dcrpool shut down.")
return nil
}

func main() {
// Work around defer not working after os.Exit()
if err := realMain(); err != nil {
os.Exit(1)
}
}

0 comments on commit 433a31b

Please sign in to comment.