1.示例代码

package main

import (
"fmt"
"io"
"os"
"os/exec"
)


func main() {
// "ls -la / " 默认阻塞方式运行
// 学习参考地址: https://golang.google.cn/pkg/os/exec/
cmd := exec.Command("bash","-c","ping www.baidu.com -c 8")
//output,err := cmd.Output() //默认阻塞方式运行
stdout, err := cmd.StdoutPipe()
if err == nil {
cmd.Start()
fmt.Println("started")
io.Copy(os.Stdout,stdout)
}else {
fmt.Println(err)
}
cmd.Wait() //等待进程结束
fmt.Println(cmd.ProcessState.ExitCode()) //获取进程推出信号
}

2.编译操作

bogon$ set GOOS=linux  #交叉编译
bogon$ go mod init testexec
go: creating new go.mod: module daySignal
go: to add module requirements and sums:
go mod tidy
bogon$ go mod tidy
bogon$ go build


3.测试验证

bogon:testexec  lijianxing$ ./testexec 
started
PING www.a.shifen.com (110.242.68.4): 56 data bytes
64 bytes from 110.242.68.4: icmp_seq=0 ttl=54 time=15.166 ms
64 bytes from 110.242.68.4: icmp_seq=1 ttl=54 time=13.326 ms
64 bytes from 110.242.68.4: icmp_seq=2 ttl=54 time=18.166 ms
64 bytes from 110.242.68.4: icmp_seq=3 ttl=54 time=24.788 ms
64 bytes from 110.242.68.4: icmp_seq=4 ttl=54 time=18.982 ms
64 bytes from 110.242.68.4: icmp_seq=5 ttl=54 time=18.637 ms
64 bytes from 110.242.68.4: icmp_seq=6 ttl=54 time=13.384 ms
64 bytes from 110.242.68.4: icmp_seq=7 ttl=54 time=13.413 ms

--- www.a.shifen.com ping statistics ---
8 packets transmitted, 8 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 13.326/16.983/24.788/3.732 ms
0