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/)