From 4b3ea15fedf3c156b88095628bdaf0bbedca7798 Mon Sep 17 00:00:00 2001 From: Kimmo Lehto Date: Thu, 29 Jul 2021 15:05:34 +0300 Subject: [PATCH] Avoid closing the Command cancel channel twice --- command.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/command.go b/command.go index 1f57d34..36f2ace 100644 --- a/command.go +++ b/command.go @@ -37,6 +37,7 @@ type Command struct { done chan struct{} cancel chan struct{} + once sync.Once } func newCommand(shell *Shell, ids string) *Command { @@ -104,20 +105,25 @@ func (c *Command) check() error { // Close will terminate the running command func (c *Command) Close() error { - if err := c.check(); err != nil { + var err error + + if err = c.check(); err != nil { return err } - select { // close cancel channel if it's still open - case <-c.cancel: - default: - close(c.cancel) + if _, ok := <-c.cancel; !ok { + return nil // channel already closed, do not send a signal } - request := NewSignalRequest(c.client.url, c.shell.id, c.id, &c.client.Parameters) - defer request.Free() + c.once.Do(func() { + close(c.cancel) + + request := NewSignalRequest(c.client.url, c.shell.id, c.id, &c.client.Parameters) + defer request.Free() + + _, err = c.client.sendRequest(request) + }) - _, err := c.client.sendRequest(request) return err }