dqfxao2898 2015-04-09 02:34
浏览 221
已采纳

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

I read the explanation from golang.org, it says like below.

// 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

I'm not very understand about it ? For example I have such code below.

cmd := &exec.Cmd{
    Path: init,
    Args: initArgs,
}
cmd.Stdin = Stdin
cmd.Stdout = Stdout
cmd.Stderr = Stderr
cmd.Dir = Rootfs
cmd.ExtraFiles = []*os.File{childPipe}

Is that mean, since I have written a childpipe in cmd.ExtraFiles = []*os.File{childPipe}, I can use it by writing fd 3 directly.

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

Thanks if anyone can give some help!

  • 写回答

1条回答 默认 最新

  • dongsu3664 2015-04-12 23:24
    关注

    Correct; you can read from the pipe by creating a new *File whose file descriptor is that of the child pipe. Below is a example of piping data from the child process to the parent:

    Parent:

    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
    ", data)
    }
    

    Child:

    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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)