From 576ee1fe4fd7f58e8719ec58044105cdacfc054c Mon Sep 17 00:00:00 2001 From: Sergey Matveev Date: Sun, 27 Nov 2022 23:41:06 +0300 Subject: [PATCH] Wait for background jobs before finish message --- cmd/btrtrc/main.go | 11 ++++++++--- cmd/btrtrc/status.go | 11 +++++++++-- cmd/btrtrc/txstats.go | 11 +++++++++-- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/cmd/btrtrc/main.go b/cmd/btrtrc/main.go index 72897644..35880d9e 100644 --- a/cmd/btrtrc/main.go +++ b/cmd/btrtrc/main.go @@ -68,22 +68,27 @@ func main() { defer client.Close() needsShutdown := make(chan os.Signal) + overallStatusCancel := make(chan struct{}) + txStatsDumperCancel := make(chan struct{}) signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT) go func() { <-needsShutdown - txStatsDumpAll(client) + overallStatusCancel <- struct{}{} + txStatsDumperCancel <- struct{}{} client.Close() }() os.MkdirAll(path.Join(FIFOsDir, PeersDir), 0777) os.MkdirAll(path.Join(FIFOsDir, FilesDir), 0777) log.Println("started", client.PublicIPs()) - go overallStatus(client) + go overallStatus(client, overallStatusCancel) go fifoList(client) go fifoDHTList(client) go fifoAdd(client) go fifoDel(client) - go txStatsDumper(client) + go txStatsDumper(client, txStatsDumperCancel) <-client.Closed() + <-overallStatusCancel + <-txStatsDumperCancel log.Println("finished") } diff --git a/cmd/btrtrc/status.go b/cmd/btrtrc/status.go index ea8ac93a..f040d554 100644 --- a/cmd/btrtrc/status.go +++ b/cmd/btrtrc/status.go @@ -8,9 +8,16 @@ import ( "github.com/dustin/go-humanize" ) -func overallStatus(c *torrent.Client) { +func overallStatus(c *torrent.Client, cancel chan struct{}) { + tick := time.Tick(time.Second) var prev torrent.ConnStats - for range time.Tick(time.Second) { + for { + select { + case <-cancel: + close(cancel) + return + case <-tick: + } stats := c.ConnStats() var peers int for _, t := range c.Torrents() { diff --git a/cmd/btrtrc/txstats.go b/cmd/btrtrc/txstats.go index 2249e566..6ce62bab 100644 --- a/cmd/btrtrc/txstats.go +++ b/cmd/btrtrc/txstats.go @@ -60,8 +60,15 @@ func txStatsDumpAll(c *torrent.Client) { } } -func txStatsDumper(c *torrent.Client) { - for range time.Tick(10 * time.Second) { +func txStatsDumper(c *torrent.Client, cancel chan struct{}) { + tick := time.Tick(10 * time.Second) + for { txStatsDumpAll(c) + select { + case <-cancel: + close(cancel) + return + case <-tick: + } } } -- 2.48.1