gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:28 30 4
gpt4 key购买 nike

我想做什么:

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com