From d07f5e449aa6715b83b66c7b755c596018eb88d3 Mon Sep 17 00:00:00 2001 From: "chen.yang" Date: Wed, 11 Aug 2021 14:31:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20=E5=B8=A6=20Cancel=20?= =?UTF-8?q?=E7=9A=84=E5=A4=96=E9=83=A8=E5=91=BD=E4=BB=A4=E8=B0=83=E7=94=A8?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: chen.yang --- .../Go/Package/OS/Exec/Golang_执行外部程序.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md b/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md index e19fb8b..f1e8450 100644 --- a/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md +++ b/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md @@ -2,6 +2,8 @@ 需要使用 os/exec 包。 +## 1.基本用法 + 示例如下: ```go @@ -28,3 +30,31 @@ exec.Cmd 有 Start、Wait、Run、Output 等方法,其中 * Wait:阻塞进程,等待命令执行结束, 经常与 Star 配合使用; * Run:阻塞进程,直到命令执行结束,相当于 Start+Wait 的组合; * Output:阻塞进程,直到命令执行结束,比 Run 方法多返回程序的 stdout。 + +## 2.带 Cancel 的外部命令调用 + +```go +func MakeCmdWithCancel(name string, arg ...string) (*exec.Cmd, context.CancelFunc) { + ctx, cancel := context.WithCancel(context.Background()) + cmd := exec.CommandContext(ctx, name, arg...) + cmd.Env = append(cmd.Env, "USER=root") + cmd.Env = append(cmd.Env, "HOME=/home/root") + cmd.Env = append(cmd.Env, "SHELL=/bin/sh") + cmd.Env = append(cmd.Env, "SHLVL=1") + cmd.Env = append(cmd.Env, "LOGNAME=root") + cmd.Env = append(cmd.Env, "XDG_RUNTIME_DIR=/run/user/0") + cmd.Env = append(cmd.Env, "PATH=/usr/local/bin:/usr/bin:/bin:/xt/scripts:/usr/local/sbin:/usr/sbin:/sbin:/xt/scripts") + return cmd, cancel +} + +func main() { + // Sleep 20s + sleep, cancel := MakeCmdWithCancel("sleep", "20") + sleep.Start() + // 3s 后 Cancel 掉 + time.Sleep(3 * time.Second) + cancel() + // 会立刻退出 + sleep.Wait() +} +```