golang 使用Golang访问Exec'd进程的StdIn

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 使用Golang访问Exec'd进程的StdIn相关的知识,希望对你有一定的参考价值。

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
}
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.")
}

golang golang exec的用法

func (s *SCMClient) Push2Center(sourceFile, targetFile string) {
	command := fmt.Sprintf("%s -a %s:%s -t scm -s %s -d %s -x 60 -o 132", SDN_SEND_SCRIPT, s.CenterDomain, s.Port, sourceFile, targetFile)
	cmd := exec.Command(command)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		glog.V(2).Info("[Command exec] Error: %v %q %q", err, stdout.Bytes(), stderr.Bytes())
		return
	}

	outs := string(stdout.Bytes())
	errs := string(stderr.Bytes())

	if len(outs) == 0 || len(errs) != 0 {
		glog.V(2).Info("[Command exec] Error: %s %s", outs, errs)
		return
	}

	glog.V(2).Info("Scm push result: ", string(stdout.Bytes()))
}

以上是关于golang 使用Golang访问Exec'd进程的StdIn的主要内容,如果未能解决你的问题,请参考以下文章

Golang os/exec 实现

003-golang 调用外部命令

防止 Ctrl+C 中断 Golang 中的 exec.Command

golang 在golang中管道exec.Cmd(示例按其扩展名对目录下的所有常规文件进行排序)

在 Golang 中运行 exec.Command 时如何调试“退出状态 1”错误

Golang exec:stat:文件被移动到那里后没有这样的文件或目录