Safely handle Ctrl-C in Golang

· Read in about 1 min · (124 Words)

A framework for safely handling Ctrl-C in Golang.


cancel := make(chan struct{})

// do some jobs
chWaitJobs := make(chan int)
go func(cancel chan ) { // one example
    // do jobs that may take long time
LOOP:
    for {
        select {
        case <-cancel:
            break LOOP
        default:
        }

        // do something
    }

    <- chWaitJobs
}(cancel)


chExitSignalMonitor := make(chan struct{})
cleanupDone := make(chan int)

signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)

go func() {
    select {
    case <-signalChan:
        log.Criticalf("received an interrupt, cleanning up ...")

        // broadcast cancel signal, so other jobs can exit safely
        close(cancel)

        // cleanning work

        cleanupDone <- 1
        return
    case <-chExitSignalMonitor:
        cleanupDone <- 1
        return
    }
}()

// wait jobs done
<-chWaitJobs

close(chExitSignalMonitor)
<-cleanupDone

Reference