dongtiaobeng7901 2014-04-19 05:54
浏览 507

我如何在golang中将stdin发送给exec cmd

I have this code

subProcess := exec.Cmd{
    Path: execAble,
    Args: []string{
        fmt.Sprintf("-config=%s", *configPath),
        fmt.Sprintf("-serverType=%s", *serverType),
        fmt.Sprintf("-reload=%t", *reload),
        fmt.Sprintf("-listenFD=%d", fd),
    },
    Dir: here,
}
subProcess.Stdout = os.Stdout
subProcess.Stderr = os.Stderr
logger.Info("starting  subProcess:%s ", subProcess.Args)

if err := subProcess.Run(); err != nil {
    logger.Fatal(err)
}

and then I do os.Exit(1) to stop the main process

I can get output from the subprocess

but I also want to put stdin to

I try

subProcess.Stdin = os.Stdin

but it does not work

  • 写回答

3条回答 默认 最新

  • duan19850312 2014-04-19 07:46
    关注

    I made a simple program (for testing). It reads a number and writes the given number out.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        fmt.Println("Hello, What's your favorite number?")
        var i int
        fmt.Scanf("%d
    ", &i)
        fmt.Println("Ah I like ", i, " too.")
    }
    

    And here is the modified code

    package main
    
    import (
        "fmt"
        "io"
        "os"
        "os/exec"
    )
    
    func main() {
        subProcess := exec.Command("go", "run", "./helper/main.go") //Just for testing, replace with your subProcess
    
        stdin, err := subProcess.StdinPipe()
        if err != nil {
            fmt.Println(err) //replace with logger, or anything you want
        }
        defer stdin.Close() // the doc says subProcess.Wait will close it, but I'm not sure, so I kept this line
    
        subProcess.Stdout = os.Stdout
        subProcess.Stderr = os.Stderr
    
        fmt.Println("START") //for debug
        if err = subProcess.Start(); err != nil { //Use start, not run
            fmt.Println("An error occured: ", err) //replace with logger, or anything you want
        }
    
        io.WriteString(stdin, "4
    ")
        subProcess.Wait()
        fmt.Println("END") //for debug
    }
    

    You interested about these lines

    stdin, err := subProcess.StdinPipe()
    if err != nil {
        fmt.Println(err)
    }
    defer stdin.Close()
    //...
    io.WriteString(stdin, "4
    ")
    //...
    subProcess.Wait()
    

    Explanation of the above lines

    1. We gain the subprocess' stdin, now we can write to it
    2. We use our power and we write a number
    3. We wait for our subprocess to complete

    Output

    START
    Hello, What's your favorite number?
    Ah I like 4 too.
    END

    For better understanding

    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记