亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從子進程中的 `exec.Cmd` ExtraFiles fd 讀取?

如何從子進程中的 `exec.Cmd` ExtraFiles fd 讀???

Go
DIEA 2021-09-27 18:30:41
我從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/2603ExtraFiles []*os.File我不是很了解嗎?例如我在下面有這樣的代碼。cmd := &exec.Cmd{    Path: init,    Args: initArgs,}cmd.Stdin = Stdincmd.Stdout = Stdoutcmd.Stderr = Stderrcmd.Dir = Rootfscmd.ExtraFiles = []*os.File{childPipe}那是說,既然我已經寫了childpipe cmd.ExtraFiles = []*os.File{childPipe},我可以寫的fd使用它3直接。pipe = os.NewFile(uintptr(3), "pipe")json.NewEncoder(pipe).Encode(newThing)謝謝如果有人可以提供一些幫助!
查看完整描述

1 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

正確的; 您可以通過創建一個新*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")

}


查看完整回答
反對 回復 2021-09-27
  • 1 回答
  • 0 關注
  • 327 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號