繁体   English   中英

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

[英]How can I read from `exec.Cmd` ExtraFiles fd in child process?

我从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}

就是说,由于我已经在cmd.ExtraFiles = []*os.File{childPipe}编写了一个子管道, cmd.ExtraFiles = []*os.File{childPipe}可以通过直接编写fd 3来使用它。

pipe = os.NewFile(uintptr(3), "pipe")
json.NewEncoder(pipe).Encode(newThing)

谢谢大家的帮助!

正确; 您可以通过创建一个新的*File来从管道中读取*File该文件的文件描述符是子管道的文件描述符。 以下是从子进程到父进程的管道数据示例:

上级:

package main

import (
    "fmt"
    "os/exec"
    "os"
    "encoding/json"
)

func main() {
    init := "child"
    initArgs := []string{"hello world"}

    r, w, err := os.Pipe()
    if err != nil {
        panic(err)
    }

    cmd := exec.Command(init, initArgs...)
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.ExtraFiles = []*os.File{w}

    if err := cmd.Start(); err != nil {
        panic(err)
    }
    var data interface{}
    decoder := json.NewDecoder(r)
    if err := decoder.Decode(&data); err != nil {
        panic(err)
    }
    fmt.Printf("Data received from child pipe: %v\n", data)
}

儿童:

package main

import (
    "os"
    "encoding/json"
    "strings"
    "fmt"
)

func main() {
    if len(os.Args) < 2 {
        os.Exit(1)
    }
    arg := strings.ToUpper(os.Args[1])

    pipe := os.NewFile(uintptr(3), "pipe")
    err := json.NewEncoder(pipe).Encode(arg)
    if err != nil {
        panic(err)
    }
    fmt.Println("This message printed to standard output, not to the pipe")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM