how can I get stdin to exec cmd in golang

后端 未结 4 1006
故里飘歌
故里飘歌 2021-02-07 06:32

I have this code

subProcess := exec.Cmd{
    Path: execAble,
    Args: []string{
        fmt.Sprintf(\"-config=%s\", *configPath),
        fmt.Sprintf(\"-serverT         


        
4条回答
  •  深忆病人
    2021-02-07 06:59

    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\n", &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\n")
        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\n")
    //...
    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

提交回复
热议问题