2013-09-03 22:21:18 -04:00
|
|
|
package asink
|
2013-08-23 00:09:03 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
var exitWaiterCount int32
|
|
|
|
var exitCalled chan int
|
|
|
|
var exitWaiterChan chan int
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
exitWaiterCount = 0
|
|
|
|
exitWaiterChan = make(chan int)
|
2013-09-02 23:35:48 -04:00
|
|
|
exitCalled = make(chan int)
|
2013-08-23 00:09:03 -04:00
|
|
|
}
|
|
|
|
|
2013-09-03 22:21:18 -04:00
|
|
|
func SetupCleanExitOnSignals() {
|
|
|
|
go setupCleanExitOnSignals()
|
|
|
|
}
|
2013-08-23 00:09:03 -04:00
|
|
|
func setupCleanExitOnSignals() {
|
|
|
|
//wait to properly close the socket when we're exiting
|
|
|
|
exitCode := 0
|
|
|
|
sig := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(sig, os.Interrupt)
|
|
|
|
defer signal.Stop(sig)
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-sig:
|
|
|
|
case exitCode = <-exitCalled:
|
|
|
|
}
|
|
|
|
|
|
|
|
for c := atomic.AddInt32(&exitWaiterCount, -1); c >= 0; c = atomic.AddInt32(&exitWaiterCount, -1) {
|
|
|
|
exitWaiterChan <- exitCode
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Exit(exitCode int) {
|
|
|
|
exitCalled <- exitCode
|
|
|
|
}
|
|
|
|
|
|
|
|
func WaitOnExit() int {
|
|
|
|
atomic.AddInt32(&exitWaiterCount, 1)
|
|
|
|
return <-exitWaiterChan
|
|
|
|
}
|