运行命令时如何从Go附加文件描述符中读取

Let's say I have a program than outputs things on file descriptor 3; something like this:

package main

import "os"

func main() {
    fd3 := os.NewFile(3, "fd3")
    fd3.Write([]byte("FOOBAR
"))
    fd3.Close()
}

Now, I want to get the output sent to file descriptor 3 from a Go program:

package main

import (
    "bufio"
    "fmt"
    "os/exec"
    "os"
)

func main() {
    cmd := exec.Command("./client")
    cmd.Stderr = os.Stderr
    fd3 := os.NewFile(3, "fd3")
    defer fd3.Close()

    cmd.ExtraFiles = []*os.File{fd3}

    err := cmd.Start()
    if err != nil {
        panic(err)
    }

    go func() {
        for {
            reader := bufio.NewReader(fd3)
            line, err := reader.ReadString('
')
            if err != nil {
                panic(err)
            }
            fmt.Print(line)
        }
    }()


    cmd.Wait()

    fmt.Println("--- END ---")
}

But that does not work as it outputs the following error:

panic: read fd3: bad file descriptor

I don't understand what's wrong with my code. Anyone willing to help?

os.NewFile doesn't actually open a file descriptor. It's really an API to wrap a fd that was given to you.

look at the godoc: http://golang.org/pkg/os/#Create (click the name Create, which currently points to this)

I think you want to call os.Create(name) and pass the fd to the child process or potentiall os.Open / os.OpenFile if you need to set mode and stuff