From 5746877e1d969f9a8f3e87e0b0bbe78fefab48b7 Mon Sep 17 00:00:00 2001
From: Matt Joiner <anacrolix@gmail.com>
Date: Sat, 4 Jan 2020 16:26:49 +1100
Subject: [PATCH] cmd/torrent: Synchronize stopping

---
 cmd/torrent/main.go | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/cmd/torrent/main.go b/cmd/torrent/main.go
index 0e15eb05..b0beba21 100644
--- a/cmd/torrent/main.go
+++ b/cmd/torrent/main.go
@@ -12,6 +12,7 @@ import (
 	"syscall"
 	"time"
 
+	"github.com/anacrolix/missinggo"
 	"golang.org/x/xerrors"
 
 	"github.com/anacrolix/log"
@@ -163,12 +164,12 @@ func statsEnabled() bool {
 	return *flags.Stats
 }
 
-func exitSignalHandlers(client *torrent.Client) {
+func exitSignalHandlers(notify *missinggo.SynchronizedEvent) {
 	c := make(chan os.Signal, 1)
 	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
 	for {
 		log.Printf("close signal received: %+v", <-c)
-		client.Close()
+		notify.Set()
 	}
 }
 
@@ -212,12 +213,21 @@ func mainErr() error {
 		clientConfig.Logger = log.Discard
 	}
 
+	var stop missinggo.SynchronizedEvent
+	defer func() {
+		stop.Set()
+	}()
+
 	client, err := torrent.NewClient(clientConfig)
 	if err != nil {
 		return xerrors.Errorf("creating client: %v", err)
 	}
 	defer client.Close()
-	go exitSignalHandlers(client)
+	go exitSignalHandlers(&stop)
+	go func() {
+		<-stop.C()
+		client.Close()
+	}()
 
 	// Write status on the root path on the default HTTP muxer. This will be bound to localhost
 	// somewhere if GOPPROF is set, thanks to the envpprof import.
@@ -238,7 +248,7 @@ func mainErr() error {
 	}
 	if flags.Seed {
 		outputStats(client)
-		select {}
+		<-stop.C()
 	}
 	outputStats(client)
 	return nil
-- 
2.51.0