c++ - 在 C++ 中使用 fifo(阻塞读取)

标签 c++ c linux fifo

我想做什么:

1.process1创建并打开写入.fifo

2.在process2中打开in.fifo进行读取

3.process1行从cin写入in.fifo

4.process2读取并计算行

5.cin(process2)输入“exit”时,关闭文件in.fifo,删除并退出

6.process2退出,因为in.fifo没有writer

在我的程序中,process2 没有退出。在 c 中,当 O_NONBLOCK 清晰时,它与读、写一起工作,但我想在 c++ 中完成

写.cpp:

#include <stdlib.h>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
    std::ofstream fifo;
    fifo.open("/home/fedor/projects/fifo2/in",ios::out);
    if(! fifo.is_open() ){
        std::cout << " error : cannot open file " << std :: endl; 
        return 1;
    }
    std::cout << " file open " << std :: endl; 
    std::string   line;   
    while (line.compare("exit") != 0 ){
         std::getline(cin, line);
         fifo << line << endl;
          /* do stuff with line */
    }
    fifo.close();
    remove("/home/fedor/projects/fifo2/in");
    return 0;
}

读取.cpp:

#include <stdlib.h>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
    std::ifstream fifo;
    fifo.open("/home/fedor/projects/fifo2/in",ifstream::in);
        if(! fifo.is_open() ){
        std::cout << " error : cannot open file " << std :: endl; 
        return 1;
    }
    std::cout << " file open " << std :: endl; 
    std::string   line;
    bool done = false;
    while (!done)
        {
        while (std::getline(fifo, line))
        {
            cout << line << endl;
            /* do stuff with line */
        }
        if (fifo.eof())
        {
            fifo.clear();  // Clear the EOF bit to enable further reading
        }
        else
        {
            done = true;
        }
    }
    return 0;
}

我找不到在哪里可以阅读有关阻止流读取的信息,例如 http://linux.die.net/man/3/read关于阻塞读取

如果process2如果输入“exit”就关闭了,像process1是生命锁吗? (它是在读取时阻塞,还是只是尝试并尝试读取)

最佳答案

无法使用 C++ 标准库做您想做的事,因为在 C++ 中没有进程和文件共享的概念。您必须使用特定于操作系统的 API,这很可能是 C(如 open()),但理论上它们可以是 C++。

关于c++ - 在 C++ 中使用 fifo(阻塞读取),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25546619/

相关文章:

c - 在线程内实现计时器的最佳方法是什么?

c++ - 为什么我们在定义指针时使用 "type * var"而不是 "type & var"?

c - C 中的错误;方法分割错误

c - 为什么我的链表冒泡排序函数有时会输出错误的结果,有时又看起来像是无限循环?

c - 从 C 代码设置 ALSA 主音量

c - Linux O_PATH 文件描述符的语义?

linux - CentOS 7.2的apache无法卸载

python - 如何从给定模型中获取 Graph(或 GraphDef)?

c++ - Qt串口读取字符串不好

c++ - 对指针数组的引用