-->

从命名管道读取连续的数据(Reading continuous data from a named

2019-10-22 14:57发布

我一直在试图从命名管道读取连续的数据。 但由于某些原因,如果我不把延迟,接收器将只是停止阅读,只有黑屏几样后显示。

我需要发送有可能以毫秒为单位改变连续的数据,所以这就是为什么把延迟是行不通的。 我想先用一个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;
}

这有什么错我的做法? 这有什么用管的两个程序之间持续沟通的最佳方式是什么?

Answer 1:

首先,你不需要打开/关闭管道的每个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读取字符串。 在这种情况下,它会从提取的字符流和任何一个空白字符遇到或遇到结束流就立即停止。 从广义上讲,这让“一字一句”回读输入。



文章来源: Reading continuous data from a named pipe