簡體   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