Running main program indefinitely in go

  Kiến thức lập trình

I’m a bit new to Golang so can someone help me with my newbie question?

My main function starts with two separate go routines. The program should run forever until is killed of course.

What is the effective way to start the program and run it indefinitely?
Also, what will be the impact if some of the routines are terminated for some reason?

What I found is that I can use select {} to block the main routine but I’m not sure if that’s safe enough.

func main() {
    go handleUnixSignal()

    appConf, err := config.ReadConfiguration()
    if err != nil {
        logrus.Fatalln(err)
    }

    // connect to database
    db := database.NewDB(dbConf)
    err = db.Connect()
    if err != nil {
        logrus.Fatalln(err)
    }

    go MyRoutine_1(db, appConf)
    go MyRoutine_2(db, appConf)

}

func handleUnixSignal() {
    sigs := make(chan os.Signal, 1)

    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

    done := make(chan bool, 1)
    go func() {
        sig := <-sigs
        logrus.Infoln("System signal received:", sig)
        logrus.Fatalln("Service killed")
    }()
    <-done

    logrus.Infoln("Done cleaning. Exiting process")
}

1

LEAVE A COMMENT