【问题标题】:How can I read from `exec.Cmd` ExtraFiles fd in child process?如何从子进程中的 `exec.Cmd` ExtraFiles fd 中读取?
【发布时间】:2015-04-09 02:34:15
【问题描述】:

我阅读了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}写了一个childpipe,直接写fd3就可以使用了。

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

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

【问题讨论】:

    标签: go


    【解决方案1】:

    正确;您可以通过创建一个新的*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")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多