【问题标题】:how to call cancel() when using exec.CommandContext in a goroutine在 goroutine 中使用 exec.CommandContext 时如何调用 cancel()
【发布时间】:2018-09-15 15:45:39
【问题描述】:

我想按需取消正在运行的命令,为此,我正在尝试,exec.CommandContext,目前正在尝试:

https://play.golang.org/p/0JTD9HKvyad

package main

import (
    "context"
    "log"
    "os/exec"
    "time"
)

func Run(quit chan struct{}) {
    ctx, cancel := context.WithCancel(context.Background())
    cmd := exec.CommandContext(ctx, "sleep", "300")
    err := cmd.Start()
    if err != nil {
        log.Fatal(err)
    }

    go func() {
        log.Println("waiting cmd to exit")
        err := cmd.Wait()
        if err != nil {
            log.Println(err)
        }
    }()

    go func() {
        select {
        case <-quit:
            log.Println("calling ctx cancel")
            cancel()
        }
    }()
}

func main() {
    ch := make(chan struct{})
    Run(ch)
    select {
    case <-time.After(3 * time.Second):
        log.Println("closing via ctx")
        ch <- struct{}{}
    }
}

我面临的问题是cancel()被调用但进程没有被杀死,我的猜测是主线程先退出,不要等待cancel()正确终止命令,主要是因为如果我在main 函数的末尾使用time.Sleep(time.Second),它会退出/终止正在运行的命令。

关于我如何wait 确保在退出之前不使用sleep 命令已被终止的任何想法?成功杀死命令后,cancel() 可以在频道中使用吗?

在尝试使用单个 goroutine 时,我尝试了这个:https://play.golang.org/p/r7IuEtSM-gLcmd.Wait() 似乎一直阻塞select 并且无法调用cancel()

【问题讨论】:

  • 您必须在Wait 之后写上quit 才能发出远程进程终止的信号。在您的 main 中,在选择之后,在 quit 上添加一个读取操作以捕获该新信号并退出您的程序。

标签: go


【解决方案1】:

在 Go 中,如果到达 main 方法(在 main 包中)的末尾,程序将停止。这种行为在 Go 语言规范中的 section on program execution 下进行了描述(强调我自己的):

程序执行从初始化main 包开始,然后调用函数main。当该函数调用返回时,程序退出。 它不会等待其他(非主)goroutine 完成。


缺陷

我将考虑您的每个示例及其相关的控制流缺陷。您将在下面找到指向 Go 游乐场的链接,但这些示例中的代码不会在限制性游乐场沙箱中执行,因为找不到 sleep 可执行文件。复制并粘贴到您自己的环境中进行测试。

多个goroutine示例

case <-time.After(3 * time.Second):
        log.Println("closing via ctx")
        ch <- struct{}{}

在计时器触发并且您向 goroutine 发出信号是时候杀死孩子并停止工作后,没有什么会导致 main 方法阻塞并等待它完成,所以它返回。按照语言规范,程序退出。

调度程序可能会在通道传输后触发,因此main 退出和其他 goroutines 唤醒以接收来自ch 之间可能存在竞争。然而,假设任何特定的行为交错是不安全的——而且,出于实际目的,在main 退出之前不太可能发生任何有用的工作。 sleep 子进程将是 orphaned;在 Unix 系统上,操作系统通常会将进程重新作为init 进程的父进程。

单个 goroutine 示例

在这里,你遇到了相反的问题:main 没有返回,所以子进程没有被杀死。这种情况只有在子进程退出时(5分钟后)才能解决。出现这种情况是因为:

  • Run 方法中对cmd.Wait 的调用是阻塞调用(docs)。 select 语句被阻塞等待cmd.Wait 返回错误值,因此无法从quit 通道接收。
  • quit 通道(在main 中声明为ch)是一个无缓冲通道。无缓冲通道上的发送操作将阻塞,直到接收器准备好接收数据。来自language spec on channels(再次强调我自己的):

    容量(元素数量)设置通道中缓冲区的大小。如果容量为零或不存在,则通道无缓冲,只有在发送方和接收方都准备好时才能成功通信

    由于Runcmd.Wait中被阻塞,所以没有准备好的接收器来接收main方法中的ch &lt;- struct{}{}语句在通道上传输的值。 main 阻塞等待传输此数据,从而阻止进程返回。

我们可以通过小的代码调整来演示这两个问题。

cmd.Wait 被阻塞

要公开cmd.Wait 的阻塞特性,请声明以下函数并使用它来代替Wait 调用。这个函数是一个包装器,其行为与cmd.Wait 相同,但有额外的副作用来打印 STDOUT 发生的事情。 (Playground link):

func waitOn(cmd *exec.Cmd) error {
    fmt.Printf("Waiting on command %p\n", cmd)
    err := cmd.Wait()
    fmt.Printf("Returning from waitOn %p\n", cmd)
    return err
}

// Change the select statement call to cmd.Wait to use the wrapper
case e <- waitOn(cmd):

运行此修改后的程序后,您将观察到控制台的输出Waiting on command &lt;pointer&gt;。计时器触发后,您将观察到输出 calling ctx cancel,但没有相应的 Returning from waitOn &lt;pointer&gt; 文本。这只会在子进程返回时发生,您可以通过将睡眠持续时间减少到更小的秒数(我选择 5 秒)来快速观察到。

在退出频道发送,ch,块

main 无法返回,因为用于传播退出请求的信号通道没有缓冲,并且没有相应的监听器。通过换行:

    ch := make(chan struct{})

    ch := make(chan struct{}, 1)

main 中通道上的发送将继续(到通道的缓冲区),main 将退出——与多 goroutine 示例的行为相同。但是,这个实现仍然存在问题:在main 返回之前,不会从通道的缓冲区中读取值来实际开始停止子进程,因此子进程仍然是孤立的。


固定版本

我为您制作了一个固定版本,代码如下。还有一些风格上的改进,可以将您的示例转换为更惯用的 go:

  • 不需要通过通道间接指示何时停止。相反,我们可以通过将上下文和取消函数的声明提升到main 方法来避免声明通道。可以在适当的时候直接取消上下文。

    我保留了单独的 Run 函数来演示以这种方式传递上下文,但在许多情况下,它的逻辑可以嵌入到 main 方法中,并生成一个 goroutine 来执行 cmd.Wait 阻塞调用.

  • main 方法中的select 语句是不必要的,因为它只有一个case 语句。
  • 引入sync.WaitGroup 是为了显式解决main 在子进程(在单独的goroutine 中等待)被杀死之前退出的问题。等待组实现一个计数器;对 Wait 的调用会阻塞,直到所有 goroutine 完成工作并调用 Done
package main

import (
    "context"
    "log"
    "os/exec"
    "sync"
    "time"
)

func Run(ctx context.Context) {
    cmd := exec.CommandContext(ctx, "sleep", "300")
    err := cmd.Start()
    if err != nil {
        // Run could also return this error and push the program
        // termination decision to the `main` method.
        log.Fatal(err)
    }

    err = cmd.Wait()
    if err != nil {
        log.Println("waiting on cmd:", err)
    }
}

func main() {
    var wg sync.WaitGroup
    ctx, cancel := context.WithCancel(context.Background())

    // Increment the WaitGroup synchronously in the main method, to avoid
    // racing with the goroutine starting.
    wg.Add(1)
    go func() {
        Run(ctx)
        // Signal the goroutine has completed
        wg.Done()
    }()

    <-time.After(3 * time.Second)
    log.Println("closing via ctx")
    cancel()

    // Wait for the child goroutine to finish, which will only occur when
    // the child process has stopped and the call to cmd.Wait has returned.
    // This prevents main() exiting prematurely.
    wg.Wait()
}

(Playground link)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 2013-08-18
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多