如何从子进程中的 `exec.Cmd` ExtraFiles fd 读取?

我从golang.org阅读了解释,它如下所示。


// ExtraFiles specifies additional open files to be inherited by the

// new process. It does not include standard input, standard output, or

// standard error. If non-nil, entry i becomes file descriptor 3+i.

//

// BUG: on OS X 10.6, child processes may sometimes inherit unwanted fds.

// http://golang.org/issue/2603

ExtraFiles []*os.File

我不是很了解吗?例如我在下面有这样的代码。


cmd := &exec.Cmd{

    Path: init,

    Args: initArgs,

}

cmd.Stdin = Stdin

cmd.Stdout = Stdout

cmd.Stderr = Stderr

cmd.Dir = Rootfs

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

那是说,既然我已经写了childpipe cmd.ExtraFiles = []*os.File{childPipe},我可以写的fd使用它3直接。


pipe = os.NewFile(uintptr(3), "pipe")

json.NewEncoder(pipe).Encode(newThing)

谢谢如果有人可以提供一些帮助!


DIEA
浏览 300回答 1
1回答

素胚勾勒不出你

正确的; 您可以通过创建一个新*File的文件描述符是子管道的文件描述符来从管道中读取。下面是从子进程到父进程的管道数据示例:家长:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os/exec"&nbsp; &nbsp; "os"&nbsp; &nbsp; "encoding/json")func main() {&nbsp; &nbsp; init := "child"&nbsp; &nbsp; initArgs := []string{"hello world"}&nbsp; &nbsp; r, w, err := os.Pipe()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; cmd := exec.Command(init, initArgs...)&nbsp; &nbsp; cmd.Stdin = os.Stdin&nbsp; &nbsp; cmd.Stdout = os.Stdout&nbsp; &nbsp; cmd.Stderr = os.Stderr&nbsp; &nbsp; cmd.ExtraFiles = []*os.File{w}&nbsp; &nbsp; if err := cmd.Start(); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; var data interface{}&nbsp; &nbsp; decoder := json.NewDecoder(r)&nbsp; &nbsp; if err := decoder.Decode(&data); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("Data received from child pipe: %v\n", data)}孩子:package mainimport (&nbsp; &nbsp; "os"&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "strings"&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; if len(os.Args) < 2 {&nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; }&nbsp; &nbsp; arg := strings.ToUpper(os.Args[1])&nbsp; &nbsp; pipe := os.NewFile(uintptr(3), "pipe")&nbsp; &nbsp; err := json.NewEncoder(pipe).Encode(arg)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("This message printed to standard output, not to the pipe")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go