GolangNote

Golang笔记

Golang 使用 channel 等待 exec.Cmd 返回的消息

Permalink

启动一个 goroutine 等待进程,使用 select 等待 goroutine 完成的消息或超时处理。

Go: exec.Cmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

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

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	done := make(chan struct{})

	cmd := exec.CommandContext(ctx, "sleep", "300")

	go func() {
		defer close(done)
		err := cmd.Start()
		if err != nil {
			log.Fatal(err)
		}
		err = cmd.Wait()
		if err != nil {
			log.Println("waiting on cmd:", err)
		}
	}()

	select {
	case <-done:
		// cmd.Wait() completed.
	case <-time.After(3 * time.Second):
		fmt.Println("Exit Signal")
		_ = cmd.Process.Kill()
	}

	cancel()
}

本文网址: https://golangnote.com/topic/279.html 转摘请注明来源

Related articles

golang共享数据用Mutex 或 Channel

在go 里,多线程对共享数据的操作一般要使用Mutex 或 Channel 来加锁或隔离通信。下面是一个使用Mutex 和 Channel 比较的例子。...

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

golang Selenium WebDriver 使用记录

Selenium WebDriver 直接通过浏览器自动化的本地接口来调用浏览器,以达到模拟浏览器行为的操作,如点击、选择、鼠标移动等。下面是记录个人使用golang 驱动的记录。...

Write a Comment to "Golang 使用 channel 等待 exec.Cmd 返回的消息"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms