Re-factor clean exiting to be usable in the client also

This commit is contained in:
2013-09-03 22:21:18 -04:00
parent 4eb75e1db1
commit 2dcd08d502
3 changed files with 10 additions and 5 deletions

View File

@ -1,44 +0,0 @@
package main
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)
exitCalled = make(chan int)
go setupCleanExitOnSignals()
}
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
}

View File

@ -1,6 +1,7 @@
package main
import (
"asink"
"net"
"net/http"
"net/rpc"
@ -68,7 +69,7 @@ func (u *UserModifier) RemoveUser(user *User, result *int) error {
type ServerStopper int
func (s *ServerStopper) StopServer(code *int, result *int) error {
Exit(*code)
asink.Exit(*code)
*result = 0
return nil
}
@ -92,5 +93,5 @@ func StartRPC(sock string, tornDown chan int, adb *AsinkDB) {
go http.Serve(l, nil)
WaitOnExit()
asink.WaitOnExit()
}

View File

@ -29,6 +29,8 @@ func init() {
if err != nil {
panic(err)
}
asink.SetupCleanExitOnSignals()
}
const sock_usage = "Socket to use to connect to the Asink server."
@ -60,7 +62,7 @@ func StartServer(args []string) {
go http.Serve(l, nil)
//TODO handle errors from http.Serve?
WaitOnExit()
asink.WaitOnExit()
<-rpcTornDown
}