[英]C++ Piped data prints out in blocks
我正在嘗試編寫一個程序,該程序將另一個程序的stdout
拆分為幾行並打印出來。
該程序連續不斷地輸出數據(每秒約800個字符)。
我已經分叉了它,並使用dup2將其stdout
發送到管道到父進程。
問題是父進程讀取數據,但每6ish秒只能以大約150行的塊的形式打印出來。
因此它會打印數據,然后持續6秒鍾不打印任何數據,然后打印更多數據,然后不打印任何數據。
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
int pipe1[2];
char readbuf[5];
string line = ">>";
if (pipe(pipe1) != 0){ //Setting up the pipe
cerr << "Pipe failed\n"; exit(1);
}
pid_t pid = fork(); //Setting up the fork
if (pid < 0){
cerr << "Fork failed\n" ;exit(-1);
}
else if (pid == 0){
//Child Process
dup2(pipe1[1], STDOUT_FILENO); //dup2()ing stdout to pipe
close(pipe1[1]); //closing other pipe connections
close(pipe1[0]);
execl("program_folder/program", "program_folder/program", NULL); //running the program
}
else{
//Parent
close(pipe1[1]); //closing write end of pipe
for (;;){
do{
if (read(pipe1[0], readbuf, 1) < 0){
cout << "read error"<<endl;
return 1;
} //Reads 1 character at a time,
line.push_back(readbuf[0]); //pushing them onto a string,
}while(readbuf[0] != '\n'); //until the new line character is reached
cout<< line; //Prints the line of data
line= ">>";
}
close(pipe1[0]);
}
return 0;
}
輸出看起來像這樣:(偏航,俯仰,側傾值)
>>ypr 63.71 -68.52 19.24
>>ypr 63.75 -68.52 19.24
>>ypr 63.78 -68.52 19.24
>>ypr 63.81 -68.52 19.24
>>ypr 63.85 -68.52 19.24
>>ypr 63.89 -68.52 19.23
>>ypr 63.93 -68.52 19.24
>>ypr 63.97 -68.52 19.24
>>ypr 64.00 -68.52 19.24
將來,我想通過套接字將它們發送到另一台計算機,並使用gnuplot等實時繪制它們。 我知道使用python會更容易,但我只想嘗試使用C。
我試過使用std :: endl; 和std :: cout.flush(); 但沒有運氣。
我在這里做錯了什么?
使用管道時,數據流中的每行輸出不再有行。 這是UNIX的一般問題。 stdout檢查輸出流是否為tty(通過調用isatty(3)
),因此它將在輸出中找到的每個\\n
或BUFSIZ
字符填充緩沖區時刷新輸出。 由於程序中有pipe(2)
d,因此不再有行緩沖,因此緩沖區將在塊塊中刷新。 您可以通過插入對fflush(stdout);
的調用來強制進行沖洗fflush(stdout);
在適當的地方(C語言)。 或如注釋中所指出的(感謝@spectras)和以下行(僅適用於C ++):
cout << "your line here" << std::flush;
(您必須編輯管道編寫器,因為您無法通過讀取器進程控制編寫器緩沖區的工作方式。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.