[英]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.