![](/img/trans.png)
[英]How redirect stdout (stderr) of child process to socket in winapi?
[英]how to get stdout of child process in realtime?
我想實時捕獲子任務的標准輸出,我的子任務是由 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 但沒有運氣。 如果我刪除“睡眠 1”,那么 output 很快。 必須有其他地方在做緩沖。 如何讓它工作?
彈出后,您可以執行以下操作:
if (fcntl(fileno(out), F_SETFL, O_NONBLOCK) < 0)
exit(1);
我現在知道為什么了。 我必須在子進程中調用 setvbuf,而不是父進程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.