拦截非终止子进程C ++的stdout

时间:2014-11-12 19:18:26

标签: c++ subprocess

我的C ++程序创建一个子进程来调用一个不终止的python脚本,但我也想通过在我的主程序C ++中检索它(python子进程)stdout来了解该子进程中发生了什么。我有以下代码。在这种情况下,我只对python程序的第一行stdout感兴趣。

FILE *fp;
char *line = (char*)malloc(1024 * sizeof(char));
int index = 0;
char c;

fp = popen("python testing.py run_for_long_time", "r");
while (true)
{
    c = fgetc(fp);
    if (c == '\n') {
        break;
    }
    line[index++] = c;
}
line[index] = '\0';
printf("Finished\n");

我注意到代码在子进程终止之前没有打印出来(但我只对子进程stdout的第一行感兴趣,所以我不想等待子进程终止)。 我怎么能用popen和文件描述符来做这个?

1 个答案:

答案 0 :(得分:0)

感谢@ArtemGr,事实证明我只需要启用python缓冲。看到 Disable output buffering

相关问题