代码之家  ›  专栏  ›  技术社区  ›  Alexis Wilke

在Go中,如何使用Pipes分配其他ExraFiles以具有多个输出流?

  •  1
  • Alexis Wilke  · 技术社区  · 5 年前

    我有一个命令,我通过Stdin向其发送数据,并期望有28个输出流(包括 Stdout ).

    所以我想用 cmd.ExtraFiles 带有a的字段 os.Pipe 对于每一个 os.ExtraFiles .

    我写了以下内容:

    backgroundContext, cancelCommand := context.WithCancel(context.Background())
    cmd := exec.CommandContext(backgroundContext, "command", args...)
    cmd.ExtraFiles = make([]*io.File, 27, 0)
    
    var outputPipe io.ReadCloser
    var inputPipe io.WriteCloser
    
    outputPipe, inputPipe, err = os.Pipe()
    cmd.ExtraFiles[0] = &inputPipe
    cmd.ExtraFiles[1] = &outputPipe
    

    最后两行生成错误,因为类型不匹配:

    ./main.go:876:26: cannot use &inputPipe (type *io.WriteCloser) as type *os.File in assignment
    ./main.go:877:26: cannot use &outputPipe (type *io.ReadCloser) as type *os.File in assignment
    

    我确信我们可以分配管道,因为例如我可以使用 StdoutPipe() 功能正常,工作正常。

    我该怎么做 os。附加文件 ?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Cerise Limón    5 年前

    问题中的代码无法编译,因为 *os.File 操作系统返回的值。管道存储在具有接口类型的变量中 io.ReadCloser io.WriteCloser .指向具有这些类型的值的指针不能分配给 *os。文件 .

    通过将返回值赋给类型为的变量来修复 *os。文件 .

    cmd.ExtraFiles = make([]*os.File, 27)
    outputPipe, inputPipe, err := os.Pipe()
    if err != nil {
        // handle error
    }
    cmd.ExtraFiles[0] = inputPipe
    cmd.ExtraFiles[1] = outputPipe
    

    奖金修复:

    • 它是 os.File ,不 io.File .
    • 分配长度和容量为27的切片。分配容量小于长度的切片是错误的。