dqfwcj0030
dqfwcj0030
2019-01-29 01:47

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

  • pipe
已采纳

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongrenzheng1619 dongrenzheng1619 2年前

    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()
    

    }

    点赞 评论 复制链接分享