dpntq48842 2018-12-18 11:11
浏览 178

捕获exec.Command的缓冲stdout输出

I'm trying to catch output of external program. Example:

#include <stdio.h>
#include <unistd.h>
#include <stddef.h>

int main() {

    int i = 0;

    while(i < 10) {
        printf("i = %i
", i++);
        usleep(2000000);
    }
    return 0;
}

And here is my main.go:

package main

import (
    "bufio"
    "io"
    "log"
    "os/exec"
)

func reecho(closer io.ReadCloser)  {
    reader := bufio.NewReader(closer)

    for {
        s, e := reader.ReadString('
')
        if e != nil {
            log.Println(e)
            break
        }
        log.Println(s)
    }
}

func main() {
    cmd := exec.Command("./infcount")
    log.Println("starting ", cmd)
    stdout, err := cmd.StdoutPipe()
    stderr, _ := cmd.StderrPipe()

    if err != nil {
        log.Fatal(err)
    }
    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }

    go reecho(stdout)
    go reecho(stderr)

    if err := cmd.Wait(); err != nil {
        log.Fatal(err)
    }
}

The problem is buffering of stdout. "reecho" get data only when 4096 bytes in stdout buffer or program is exiting(for my short example). Is there way to decrease size of buffer to catch every line of output?

Update: Same binary 'infcount' works fine when ran from shell. It writes every 'i' to the screen.

  • 写回答

1条回答 默认 最新

  • doudang4568 2018-12-18 15:45
    关注

    version of your C program that will track the output as it happens

       #include <stdio.h>
        #include <unistd.h>
        #include <stddef.h>
    
        int main() {
    
            int i = 0;
    
            while(i < 10) {
                printf("i = %i
    ", i++);
                usleep(2000000);
                fflush(stdout);
            }
            return 0;
        }
    

    If it is an existing precompiled program then stdbuf may be able to fix it, see https://www.perkin.org.uk/posts/how-to-fix-stdio-buffering.html

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?