我正在尝试将管道连接到cmd.ExtraFiles
我目前有错误的说法

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

这是我到目前为止拥有的gocode
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\n", 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\n", stdinErr)
    return stdinErr
}
cmd3.Start()
cmd2.Stdin = stdin

编辑:添加了完整范围
目标是让cmt2通过Stdin通过cmd3接受输入,并通过ExtraFiles通过cmd1输出输出

最佳答案

这里的类型不太一致。具体来说,

cmd.StdoutPipe

返回io.ReadCloser
然而
pipeR.Read

期望输入[]byte

我相信您最终希望利用ReadWriteos package函数来完成任务,如下所示:
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\n", 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()

}

关于go - 尝试通过管道传递到cmd.ExtraFiles时失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54412764/

10-17 01:31