代码测试环境
Centos 6.10 64位
go version: go1.11
概述
ffmpeg
system()system()child_process.exec()
exec.Command()
实例
下面就以我认为最常见的使用场景举例说明
查找命令绝对路径
cmdPath, _ := exec.LookPath("ls")
fmt.Printf("cmdPath=%s\n", cmdPath)
执行命令
ls -l
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
// Run 和 Start只能用一个
// Run starts the specified command and waits for it to complete.
_ = cmd.Run()
// Start starts the specified command but does not wait for it to complete.
// _ = cmd.Start()
// _ = cmd.Wait()
注意Run和Start()方法只能用一个, Run方法是同步的, 会在命令执行完后才返回;
Start()方法是异步的, 会立即返回, 可以调用Wait()方法"等待"命令执行完成.
使用管道连接多个命令
ps -ef | grep -i ssh
ps := exec.Command("ps", "-ef")
grep := exec.Command("grep", "-i", "ssh")
r, w := io.Pipe() // 创建一个管道
defer r.Close()
defer w.Close()
ps.Stdout = w // ps向管道的一端写
grep.Stdin = r // grep从管道的一端读
var buffer bytes.Buffer
grep.Stdout = &buffer // grep的输出为buffer
_ = ps.Start()
_ = grep.Start()
ps.Wait()
w.Close()
grep.Wait()
io.Copy(os.Stdout, &buffer) // buffer拷贝到系统标准输出
上述代码执行可能的输出为:
[root@mycentos cmd]# go run main.go
cmdPath=/bin/ls
total 4
-rwxr-xr-x. 1 root root 854 Jan 22 2019 main.go
root 1164 1 0 16:08 ? 00:00:00 /usr/sbin/sshd
root 3836 3830 0 17:45 pts/0 00:00:00 grep -i ssh
欢迎补充指正!