尝试通过管道传递到cmd.ExtraFiles时失败

问题描述:

I'm trying to have a pipe go to the cmd.ExtraFiles

I currently have the error saying

cannot use cmdstdout (type io.ReadCloser) as type []byte in argument to pipeR.Read
cannot use cmdstdout (type io.ReadCloser) as type []byte in argument to fd3.Write

This is the gocode I have thus far

cmd2 = exec.Command("-i", "pipe:0", "-i", "pipe:1")
cmd1 := exec.Command("command", "-o", "-")
pipeR, pipeW, _ := os.Pipe()
cmd2.ExtraFiles = []*os.File{
    pipeW,
}
cmd1.Start()
cmd1stdout, err := cmd1.StdoutPipe()
if err != nil {
    log.Printf("pipeThruError: %v
", err)
    return err
}
fd3 := os.NewFile(3, "/proc/self/fd/3")
fd3.Write(cmd1stdout)
pipeR.Read(cmd1stdout)
pipeR.Close()
pipeW.Close()
fd3.Close()
cmd3 = exec.Command("command", "-o", "-")
stdin, stdinErr := cmd3.StdoutPipe()
if stdinErr != nil {
    log.Printf("pipeThruFStdinErr: %v
", stdinErr)
    return stdinErr
}
cmd3.Start()
cmd2.Stdin = stdin

EDIT: Added full scope The goal is to have cmd2 accept input via cmd3 by Stdin, and have cmd1 output piped via ExtraFiles

我正在尝试使用管道连接到 cmd.ExtraFiles code> p >

我目前遇到错误,说 p>

 不能将cmdstdout(类型io.ReadCloser)用作pipeR参数中的[] byte类型。Read
cannot 使用cmdstdout(类型io.ReadCloser)作为fd3的参数中的[] byte类型。写入
  code>  pre> 
 
 

这是我到目前为止拥有的gocode p>

  cmd2 = exec.Command(“-i”,“ pipe:0”,“ -i”,“ pipe:1”)
cmd1:= exec.Command(“ command”,“-  o“,”-“)
pipeR,pipeW,_:= os.Pipe()
cmd2.ExtraFiles = [] * os.File {
 pipeW,
} 
cmd1.Start()
cmd1stdout,err:  = cmd1.StdoutPipe()
if err!= nil {
 log.Printf(“ pipeThruError:%v 
”,err)
 return err 
} 
fd3:= os.NewFile(3,“ / proc  /self/fd/3")
fd3.Write(cmd1stdout)
pipeR.Read(cmd1stdout)
pipeR.Close()
pipeW.Close()
fd3.Close()
cmd3 = exec.Command(“ command”  ,“ -o”,“-”)
stdin,stdinErr:= cmd3.StdoutPipe()
if stdinErr!= nil {
 log.Printf(“ pipeThruFStdinErr:%v 
”,s  tdinErr)
返回stdinErr 
} 
cmd3.Start()
cmd2.Stdin = stdin 
  code>  pre> 
 
 

编辑:已添加完整范围 目标是拥有cmd2 通过 Stdin code>通过cmd3接受输入,并通过 ExtraFiles code> p> div>通过cmd1输出

The types don't quite line up here. Specifically,

cmd.StdoutPipe

returns an io.ReadCloser

whereas

pipeR.Read

is expecting an []byte as input.

I believe you are ultimately looking to utilize the Read and Write functions of the os package to accomplish your task as shown below:

package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("command", "-o", "-")
    pipeR, pipeW, _ := os.Pipe()
    cmd.ExtraFiles = []*os.File{
        pipeW,
    }
    cmd.Start()
    cmdstdout, err := cmd.StdoutPipe()
    if err != nil {
        log.Printf("pipeThruError: %v
", err)
        os.Exit(1)
    }

    buf := make([]byte, 100)
    cmdstdout.Read(buf)

    pipeR.Close()
    pipeW.Close()
    fd3 := os.NewFile(3, "/proc/self/fd/3")
    fd3.Write(buf)
    fd3.Close()

}