導致這個問題的原因是管道符 |
不能寫在 exec.Command()
中,要分開執行兩條命令。方法如下
func Demo() (err error) {
psCmd := exec.Command("ps", "aux")
psStdout, psStderr := SetCommandStd(psCmd)
err = psCmd.Run()
if err != nil {
err = errors.New(err.Error() + psStderr.String())
return
}
// 篩選
grepCmd := exec.Command("grep", "mysql")
grepCmd.Stdin = psStdout
grepStdout, grepStderr := SetCommandStd(grepCmd)
err = grepCmd.Run()
if err != nil {
err = errors.New(err.Error() + grepStderr.String())
return
}
}
func SetCommandStd(cmd *exec.Cmd) (stdout, stderr *bytes.Buffer) {
stdout = &bytes.Buffer{}
stderr = &bytes.Buffer{}
cmd.Stdout = stdout
cmd.Stderr = stderr
return
}