douhandie6615 2012-10-11 22:30
浏览 18
已采纳

来自其他程序的流标准输出,不带for循环

I have a program that compile and run another program and pipe the stdout to itself for printing, since that program doesn't terminate so I need to stream it's stdout

// boilerplate ommited

func stream(stdoutPipe io.ReadCloser) {
    buffer := make([]byte, 100, 1000)
    for ;; {
        n, err := stdoutPipe.Read(buffer)
        if err == io.EOF {
            stdoutPipe.Close()
            break
        }
        buffer = buffer[0:n]
        os.Stdout.Write(buffer)
    }
}

func main() {
    command := exec.Command("go", "run", "my-program.go")
    stdoutPipe, _ := command.StdoutPipe()

    _ = command.Start()

    go stream(stdoutPipe)

    do_my_own_thing()

    command.Wait()
}

It works, but how do I do the same without repeatedly checking with a for loop, is there a library function that does the same thing?

  • 写回答

1条回答 默认 最新

  • dongma7796 2012-10-11 22:47
    关注

    You can give the exec.Cmd an io.Writer to use as stdout. The variable your own program uses for stdout (os.Stdout) is also an io.Writer.

    command := exec.Command("go", "run", "my-program.go")
    command.Stdout = os.Stdout
    command.Start()
    command.Wait()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Ros2 moveit2 Windows环境配置,有偿,价格可商议。
  • ¥15 有关“完美的代价”问题的代码漏洞
  • ¥15 请帮我看一下这个简易化学配平器的逻辑有什么问题吗?
  • ¥15 暴力法无法解出,可能要使用dp和数学知识
  • ¥15 wpf通过绑定控件自身的值,来实现背景颜色的切换
  • ¥15 CDH6.3 运行hive -e hive -e "show databases;"报错:hive-env.sh:行24: hbase-common.jar: 权限不够
  • ¥15 SSRS制作的报表打开报错,无法正常显示网页
  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 javaweb项目无法正常跳转