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 实现 10 进制转 N 进制

给定一个不没有重复字符的字符串,如 `[0-9,a-z]`,把一个 10 进制数字转为,该字符集的字符串。应用场合如汽车牌、顺序计数。...

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

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

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