我想开发C++中的小应用程序,Linux环境中,其执行以下操作中:写入/读取使用命名管道C++中的数据流(双)
1)获取的数据流(来自'黑盒子'的输出的一系列双打数组)并将其写入管道。黑盒可以被认为是一个ADC;
2)从管道读取数据流并将其提供给另一个需要这些数据作为标准输入的应用程序;
不幸的是,我无法找到教程或示例。我发现来实现这一点的最好方法是总结如下测试台例如:
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#define FIFO "/tmp/data"
using namespace std;
int main() {
int fd;
int res = mkfifo(FIFO,0777);
float *writer = new float[10];
float *buffer = new float[10];
if(res == 0) {
cout<<"FIFO created"<<endl;
int fres = fork();
if(fres == -1) {
// throw an error
}
if(fres == 0)
{
fd = open(FIFO, O_WRONLY);
int idx = 1;
while(idx <= 10) {
for(int i=0; i<10; i++) writer[i]=1*idx;
write(fd, writer, sizeof(writer)*10);
}
close(fd);
}
else
{
fd = open(FIFO, O_RDONLY);
while(1) {
read(fd, buffer, sizeof(buffer)*10);
for(int i=0; i<10; i++) printf("buf: %f",buffer[i]);
cout<<"\n"<<endl;
}
close(fd);
}
}
delete[] writer;
delete[] buffer;
}
的问题是,通过运行这个例子,我没有得到所有10个阵列我喂养的打印输出管道,而我总是得到总是第一个数组(由1填充)。
任何建议/更正/参考非常欢迎使其工作,并了解更多关于管道的行为。
编辑:
对不起!我在代码中发现了一个非常小的错误:在编写器部分的while循环中,我没有递增索引idx ......一旦我纠正它,我得到所有数组的打印输出。 但现在我面临着另一个问题:当使用大量的大型数组时,它们会随机打印出来(整个序列不会被打印)。仿佛读者部分无法应付作者的速度。这是新的示例代码:
#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#define FIFO "/tmp/data"
using namespace std;
int main(int argc, char** argv) {
int fd;
int res = mkfifo(FIFO,0777);
int N(1000);
float writer[N];
float buffer[N];
if(res == 0) {
cout<<"FIFO created"<<endl;
int fres = fork();
if(fres == -1) {
// throw an error
}
if(fres == 0)
{
fd = open(FIFO, O_WRONLY | O_NONBLOCK);
int idx = 1;
while(idx <= 1000) {
for(int i=0; i<N; i++) writer[i]=1*idx;
write(fd, &writer, sizeof(float)*N);
idx++;
}
close(fd);
unlink(FIFO);
}
else
{
fd = open(FIFO, O_RDONLY);
while(1) {
int res = read(fd, &buffer, sizeof(float)*N);
if(res == 0) break;
for(int i=0; i<N; i++) printf(" buf: %f",buffer[i]);
cout<<"\n"<<endl;
}
close(fd);
}
}
}
有一些机制,以使写入()等到读(实施)仍然从FIFO读数据,还是我失去了一些小事也是在这案件?
非常感谢那些已经给出了我的问题的前一个版本的答案,我已经实施了这些建议。
为什么你动态分配这些数组?另外,在写入调用中的sizeof()是错误的,它应该是sizeof(float),尽管它可能是偶然的。 –