[英]Write/Read a stream of data (double) using named pipes in C++
我正在嘗試在Linux環境中使用C ++開發一個小的應用程序,該應用程序將執行以下操作:
1)從“黑匣子”的輸出獲取數據流(一系列雙精度數組),並將其寫入管道。 黑匣子可以被認為是一個ADC。
2)從管道讀取數據流,並將其饋送到需要這些數據作為stdin的另一個應用程序;
不幸的是,我找不到教程或示例。 下面的測試平台示例總結了我發現的實現此目標的最佳方法:
#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填充)。
非常歡迎任何建議/糾正/參考,以使其起作用並了解有關管道行為的更多信息。
編輯:
對不起大家! 我在代碼中發現了一個非常瑣碎的錯誤:在writer部分的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);
}
}
}
是否有某種機制可以實現,以便使write()等到read()仍從FIFO讀取數據,或者在這種情況下我是否也遺漏了一些瑣碎的事情?
感謝您為我的問題的先前版本提供了答案,我已經實施了建議。
read
和write
的參數不正確。 正確的:
write(fd, writer, 10 * sizeof *writer);
read(fd, buffer, 10 * sizeof *buffer);
同樣,這些功能可能會執行部分讀取/寫入操作,因此代碼需要檢查返回值以確定是否必須繼續操作。
不知道為什么while( idx <= 10)
在while( idx <= 10)
循環,該循環永不結束。 即使在5GHz CPU上。 對讀者也有同樣的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.