output :=make([]byte,50)
n,err := stdout.Read(output)if err !=nil{
fmt.Printf("err:couldn't read data from the pipe %s\n",err)}
fmt.Printf("%s\n",n)
3.匿名管道
管道可以把一个命令的输出作为另一个命令的输入,go代码也可以做到
package main
import("bytes""fmt""os/exec")funcmain(){
cmd1 := exec.Command("ps","aux")
cmd2 := exec.Command("grep","root")var outputbuf1 bytes.Buffer
cmd1.Stdout =&outputbuf1
if err := cmd1.Start();err!=nil{
fmt.Printf("error:the first command can not be startup %s\n",err)return}if err := cmd1.Wait();err!=nil{
fmt.Printf("error:couldn't wait for the first command %s\n",err)return}
cmd2.Stdin =&outputbuf1
var outputbuf2 bytes.Buffer
cmd2.Stdout =&outputbuf2
if err := cmd2.Start();err!=nil{
fmt.Printf("error:the second command can not be startup %s\n",err)return}if err := cmd2.Wait();err!=nil{
fmt.Printf("error:couldn't wait for the second command %s\n",err)return}
fmt.Printf("%s\n",outputbuf2.Bytes())}
输出:(只截取前面部分)
root 6593.00.1451316018240 ?? Ss 10:16AM 0:01.31/System/Library/PrivateFrameworks/XprotectFramework.framework/Versions/A/XPCServices/XprotectService.xpc/Contents/MacOS/XprotectService
root 165961.90.043980044328 ?? Ss 8:39PM 0:00.02/Library/Manufacturer/Endpoint Agent/SEHA.app/Contents/MacOS/SEHA
root 2301.60.3454256448776 ?? Ss 10:14AM 0:14.87/usr/libexec/syspolicyd
root 1451.60.1450610412056 ?? Ss 10:14AM 0:28.81/System/Library/PrivateFrameworks/TCC.framework/Resources/tccd system