从命名管道读取连续数据

时间:2015-04-11 22:55:06

标签: python c++ ipc named-pipes fifo

我一直在尝试从命名管道中读取连续数据。但由于某些原因,如果我没有延迟,接收器将停止读取,并在几个样本后只显示空白屏幕。

我需要发送可能在几毫秒内发生变化的连续数据,这就是为什么推迟延迟不起作用的原因。我试图首先使用while循环模拟它(真正的脚本将读取财务数据)。这是我的第一次尝试:

这是发件人,一个python脚本:

import os
import time

try:
    os.remove("/tmp/pipe7")    # delete
except:
    print "Pipe already exists"
os.mkfifo("/tmp/pipe7")    # Create pipe
x = 0
while True:
    x = time.time()
    pipe = open("/tmp/pipe7", "w")
    line = str(x) + "\r\n\0"
    pipe.write(line)
    pipe.close()

    #time.sleep(1)


os.remove("/tmp/pipe7")    # delete

这是C / C ++中的接收器:

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>

#include <sys/stat.h>

#define MAX_BUF 1024


using namespace std;

int main()
{

    while(1){

        char buf[MAX_BUF];
        memset (buf, 0, sizeof(buf)); //Clearing the message buffer
        int fd = open("/tmp/pipe7", O_RDONLY);  // Open the pipe
        read(fd, buf, MAX_BUF);                         // Read the message - unblock the writing process
        cout << buf << endl;
        close(fd);                                 // Close the pipe

    }
    return 0;
}

我的方法出了什么问题?什么是使用管道在两个程序之间连续通信的最佳方式?

1 个答案:

答案 0 :(得分:2)

首先,您不需要为每个I / O操作打开/关闭管道。 最终你可能需要在每次写作后刷新输出。

然后,当您输出基于行的文本数据时,您无法真正依赖固定宽度读取来获取数据。举个例子,我只想读一个字符串 - istream应该读到下一个空格(这里是\n\r

所有这些导致喜欢(未经测试 - 提防拼写错误!):

with open("/tmp/pipe7", "w") as pipe:
    while True:
        x = time.time()
        line = str(x) + "\r\n"
        pipe.write(line)
        pipe.flush()
        # in real code, should somehow break the loop at some point

std::ifstream  pipe("/tmp/pipe7");  // Open the pipe
while(1){
    std::string istr;

    pipe >> istr;        
    cout << istr << endl;
    # In real code, should somehow break the loop at some point
}

close(fd);
重载

operator >>以从istream中读取字符串。在这种情况下,它将从流中提取字符,并在遇到空白字符或遇到流结束时立即停止。从广义上讲,这允许逐字回读输入&#34;。