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 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

golang Selenium WebDriver 使用记录

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

Golang quicktemplate 模版快速入门

Golang 有很多的模版引擎,自带的 `html/template` 也很好,大多数情况都能满足需求,只是有些逻辑、条件判断不好在模版里实现, `quicktemplate` 是个很好的选择。...

Golang 单实例实现网站多域名请求

有时候写网站,为了统一的后端,把不同业务都集中到一个后端,这时就需要处理多域名的请求,在 Go http server 里实现很简单,只需把不同域名映射到不同的 `http.Handler`。...

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

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