From d6e0a6453d75298524ff75a96973e11c2e5ab4d4 Mon Sep 17 00:00:00 2001 From: "rick.chan" Date: Mon, 21 Dec 2020 14:08:24 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20Golang=20=E6=89=A7?= =?UTF-8?q?=E8=A1=8C=E5=A4=96=E9=83=A8=E7=A8=8B=E5=BA=8F.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: rick.chan --- .../Go/Package/OS/Exec/Golang_执行外部程序.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md diff --git a/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md b/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md new file mode 100644 index 0000000..84ae8a1 --- /dev/null +++ b/Software/Development/Language/Go/Package/OS/Exec/Golang_执行外部程序.md @@ -0,0 +1,30 @@ +# Golang 执行外部程序 + +需要使用 os/exec 包。 + +示例如下: + +```go +func MakeCmd(name string, arg ...string) *exec.Cmd { + cmd := exec.Command(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, "LOGNAME=root") + cmd.Env = append(cmd.Env, "PATH=/usr/local/bin:/usr/bin:/bin:/xt/scripts:/usr/local/sbin:/usr/sbin:/sbin:/xt/scripts") + return cmd +} + +func main() { + cmd := MakeCmd("ls", "-l", "/") + output, _ := cmd.Output() + fmt.Println(output) +} +``` + +exec.Cmd 有 Start、Wait、Run、Output 等方法,其中 + +* Start:非阻塞执行; +* Wait:阻塞进程,等待命令执行结束, 经常与 Star 配合使用; +* Run:阻塞进程,直到命令执行结束,相当于 Start+Wait 的组合; +* Output:阻塞进程,直到命令执行结束,比 Run 方法多返回程序的 stdout。