dongqiu3709 2018-04-26 19:05
浏览 95

从后台go进程读取stdin会导致EOF错误

I'm writing a plugin for Micro that creates a background go process. When the background process runs, it repeatedly reads bytes from stdin - but it's always an EOF error.

In Micro, my background process is created as with the JobSpawn function, which returns an *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
}

I'd like to occasionally send data to the process. Data is passed to the stdin of the process with the Micro function 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))
}

This is my process code, which reads stdin with a bufio Reader in a for loop:

package main

import ("fmt"
    "bufio"
    "os")

func main() {
    for {
        reader := bufio.NewReader(os.Stdin)
        arr, err := reader.ReadBytes('
')
        if err != nil {
            fmt.Print(err)
        } else {
            fmt.Print(arr)
        }   
    }
}

Immediately after the job is spawned, it starts printing EOF errors. This does not happen when I run the program in my shell, before any data is sent to stdin. Nothing seems to happen when I call JobSend. I've even added a condition to not print anything if there's an error or if the data length is not greater than 0, but then I receive no output at all.

  • 写回答

1条回答 默认 最新

  • dongyiluan1718 2018-04-27 02:05
    关注

    I think you need to call StdinPipe before Run.

    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行