【问题标题】:how to get stdout of child process in realtime?如何实时获取子进程的标准输出?
【发布时间】:2021-01-08 12:49:02
【问题描述】:

我想实时捕捉子任务的标准输出,我的子任务是由popen创建的。但我发现我的代码有很大的延迟。 下面是我的例子:

#include <stdio.h>
#include <stdint.h>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <iostream>
#include <cstring>
#define BUFF_LEN (16*1024)
using namespace std;
int main()
{
    char *buf = (char*)malloc(BUFF_LEN);
    char cmd[128];
    sprintf(cmd, "while true;do echo gg;sleep 1;done");
    FILE *out = popen(cmd, "r");
    if(setvbuf(out, NULL, _IONBF, 0)) perror("setvbuf");
    while(1){
        int len = fread(buf, 1, BUFF_LEN, out);
        if(len < 0){
            cout << "read error" << endl;
            continue;
        }
        write(1, buf, len);
    }
}

我试过 setvbuf 但没有运气。如果我删除“sleep 1”,那么输出很快。必须有其他地方在做缓冲。如何让它发挥作用?

【问题讨论】:

    标签: c++ linux popen


    【解决方案1】:

    popen 之后,你可以这样做:

    if (fcntl(fileno(out), F_SETFL, O_NONBLOCK) < 0)
            exit(1);
    

    【讨论】:

      【解决方案2】:

      我现在知道为什么了。我必须在子进程中调用 setvbuf,而不是父进程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-09
        • 2010-10-29
        • 2016-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 2021-01-18
        相关资源
        最近更新 更多