Skip to content

Commit 4c9696c

Browse files
committed
[refactoring] Close history preserver file automatically on exit
1 parent 2b08b04 commit 4c9696c

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

internal/app/controller/controller.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ func (c *GameController) Run() {
7171
c.Engine.UiProtocol = c.Engine.History[len(c.Engine.History)-1].UiProtocol
7272
}
7373
}
74+
c.historyPreserver.CloseOnExit()
7475

7576
c.ApiServer.PublishState(*c.Engine.State, c.Engine.EngineState)
7677
c.ApiServer.PublishUiProtocol(c.Engine.UiProtocol)
@@ -99,7 +100,6 @@ func (c *GameController) setupTimeProvider() {
99100

100101
// mainLoop updates several states every full second and publishes the new state
101102
func (c *GameController) mainLoop() {
102-
defer c.historyPreserver.Close()
103103
for {
104104
time.Sleep(time.Millisecond * 10)
105105

internal/app/controller/engineHistory.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"io/ioutil"
77
"log"
88
"os"
9+
"os/signal"
10+
"syscall"
911
)
1012

1113
const maxHistorySize = 10
@@ -32,6 +34,18 @@ func (r *HistoryPreserver) Open() error {
3234
return nil
3335
}
3436

37+
// CloseOnExit makes sure to close the file when program exists
38+
func (r *HistoryPreserver) CloseOnExit() {
39+
var gracefulStop = make(chan os.Signal)
40+
signal.Notify(gracefulStop, syscall.SIGTERM)
41+
signal.Notify(gracefulStop, syscall.SIGINT)
42+
go func() {
43+
<-gracefulStop
44+
r.Close()
45+
os.Exit(0)
46+
}()
47+
}
48+
3549
// Close closes the history file
3650
func (r *HistoryPreserver) Close() {
3751
if r.historyFile == nil {

0 commit comments

Comments
 (0)