【发布时间】:2018-04-26 19:05:48
【问题描述】:
我正在为Micro 编写一个插件,它创建了一个后台 go 进程。当后台进程运行时,它会重复从标准输入读取字节 - 但它始终是 EOF 错误。
在 Micro 中,我的后台进程是使用 JobSpawn 函数创建的,它返回一个 *exec.cmd:
// JobSpawn starts a process with args in the background with the given callbacks
// It returns an *exec.Cmd as the job id
func JobSpawn(cmdName string, cmdArgs []string, onStdout, onStderr, onExit string, userargs ...string) *exec.Cmd {
// Set up everything correctly if the functions have been provided
proc := exec.Command(cmdName, cmdArgs...)
var outbuf bytes.Buffer
if onStdout != "" {
proc.Stdout = &CallbackFile{&outbuf, LuaFunctionJob(onStdout), userargs}
} else {
proc.Stdout = &outbuf
}
if onStderr != "" {
proc.Stderr = &CallbackFile{&outbuf, LuaFunctionJob(onStderr), userargs}
} else {
proc.Stderr = &outbuf
}
go func() {
// Run the process in the background and create the onExit callback
proc.Run()
jobFunc := JobFunction{LuaFunctionJob(onExit), string(outbuf.Bytes()), userargs}
jobs <- jobFunc
}()
return proc
}
我想偶尔向进程发送数据。数据通过微函数 JobSend 传递到进程的标准输入:
// JobSend sends the given data into the job's stdin stream
func JobSend(cmd *exec.Cmd, data string) {
stdin, err := cmd.StdinPipe()
if err != nil {
return
}
stdin.Write([]byte(data))
}
这是我的流程代码,它在 for 循环中使用 bufio 阅读器读取标准输入:
package main
import ("fmt"
"bufio"
"os")
func main() {
for {
reader := bufio.NewReader(os.Stdin)
arr, err := reader.ReadBytes('\n')
if err != nil {
fmt.Print(err)
} else {
fmt.Print(arr)
}
}
}
在生成作业后,它立即开始打印 EOF 错误。当我在我的 shell 中运行程序时,在将任何数据发送到标准输入之前,这不会发生。当我调用 JobSend 时,似乎什么也没发生。我什至添加了一个条件,如果出现错误或数据长度不大于 0,则不打印任何内容,但是我根本没有收到任何输出。
【问题讨论】: