我想開發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),儘管它可能是偶然的。 –