登录
首页 >  Golang >  Go问答

在 goroutine 中使用 exec.CommandContext 时如何调用 cancel()

来源:stackoverflow

时间:2024-04-08 15:39:34 121浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《在 goroutine 中使用 exec.CommandContext 时如何调用 cancel()》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我想按需取消正在运行的命令,为此,我正在尝试,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-gl 但 cmd.wait() 似乎一直阻塞 select 并且是无法调用 cancel()


解决方案


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

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

缺陷

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

多个 goroutine 示例

case <-time.after(3 * time.second):
        log.println("closing via ctx")
        ch <- struct{}{}

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

调度程序可能会在通道传输后触发,因此 main 退出和其他 goroutine 醒来以从 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 中被阻塞,因此没有准备好的接收器可以接收 ch <- struct{}{} 语句在 main 方法中在通道上传输的值。 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 的输出。计时器触发后,您将观察到输出 calling ctx cancel,但没有相应的 returning from waiton 文本。这种情况只会在子进程返回时发生,您可以通过将睡眠持续时间减少到更小的秒数(我选择 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

本篇关于《在 goroutine 中使用 exec.CommandContext 时如何调用 cancel()》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>