From 65aa0c6fd139aa43ab15b9c47030c5da7325f0a8 Mon Sep 17 00:00:00 2001 From: "chen.yang" Date: Wed, 11 Aug 2021 16:01:45 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=85=20=E5=A4=96=E9=83=A8?= =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E7=BB=91=E5=AE=9A=E6=A0=87=E5=87=86=E8=BE=93?= =?UTF-8?q?=E5=85=A5=E8=BE=93=E5=87=BA=20=E5=92=8C=20=E5=A4=96=E9=83=A8?= =?UTF-8?q?=E5=8F=82=E8=80=83=E8=B5=84=E6=96=99.?= 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 | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md b/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md index f1e8450..091cbe6 100644 --- a/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md +++ b/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md @@ -31,7 +31,30 @@ exec.Cmd 有 Start、Wait、Run、Output 等方法,其中 * Run:阻塞进程,直到命令执行结束,相当于 Start+Wait 的组合; * Output:阻塞进程,直到命令执行结束,比 Run 方法多返回程序的 stdout。 -## 2.带 Cancel 的外部命令调用 +## 2.外部程序绑定标准输入输出 + +```go +func MakeCmd(name string, arg ...string) *exec.Cmd { + cmd := exec.Command(name, arg...) + // 绑定标准输入输出 + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Env = append(cmd.Env, os.Getenv("USER")) + cmd.Env = append(cmd.Env, os.Getenv("HOME")) + cmd.Env = append(cmd.Env, os.Getenv("SHELL")) + cmd.Env = append(cmd.Env, os.Getenv("LOGNAME")) + cmd.Env = append(cmd.Env, os.Getenv("PATH")) + return cmd +} + +func main() { + cmd := MakeCmd("ls", "-l", "./") + cmd.Run() +} +``` + +## 3.带 Cancel 的外部命令调用 ```go func MakeCmdWithCancel(name string, arg ...string) (*exec.Cmd, context.CancelFunc) { @@ -58,3 +81,7 @@ func main() { sleep.Wait() } ``` + +## 4.外部参考资料 + +1. [Go标准库os/exec使用指南](https://honeypps.com/golang/go-standard-lib-os-exec-guide/)