Make sure we always close the state on read and write

Fix #827
pull/832/head
John Shahid 2014-08-14 10:34:33 -04:00
parent 4862e8538f
commit a9d73f5889
1 changed files with 7 additions and 4 deletions

View File

@ -32,6 +32,10 @@ type GlobalState struct {
func newGlobalState(path string) (*GlobalState, error) { func newGlobalState(path string) (*GlobalState, error) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil {
defer f.Close()
}
state := &GlobalState{ state := &GlobalState{
ServerLastRequestNumber: map[uint32]uint32{}, ServerLastRequestNumber: map[uint32]uint32{},
ShardLastSequenceNumber: map[uint32]uint64{}, ShardLastSequenceNumber: map[uint32]uint64{},
@ -51,14 +55,13 @@ func newGlobalState(path string) (*GlobalState, error) {
} }
func (self *GlobalState) writeToFile() error { func (self *GlobalState) writeToFile() error {
newFile, err := os.OpenFile(self.path+".new", os.O_CREATE|os.O_RDWR, 0644) newFile, err := os.OpenFile(self.path+".new", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
if err != nil { if err != nil {
return err return err
} }
if _, err := newFile.Seek(0, os.SEEK_SET); err != nil { // always close and ignore any errors on exit
return err defer newFile.Close()
}
if err := self.write(newFile); err != nil { if err := self.write(newFile); err != nil {
return err return err