我想要做什麼:在C++的FIFO(阻塞讀)工作
1,創建並開放供過程1
2.Open in.fifo在過程2
閱讀寫作in.fifo3.Write從CIN到in.fifo由過程1線
4.Read和cout線通過過程2
5.當輸入 「退出」 CIN(過程2)時,它關閉文件in.fifo,刪除它並退出
6.process2退出,因爲in.fifo沒有作家
在我的程序進程2不退出。在C它讀的作品,寫的時候O_NONBLOCK是清楚的,但我想這樣做在C++
write.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;
}
read.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;
}
我可以」 t找到我在哪裏可以讀取有關阻止讀取像流http://linux.die.net/man/3/read關於阻止讀取
如果process2關閉,如果輸入「退出」,就像process1是一個生命鎖? (讀取時是否阻塞,或只是嘗試讀取)
感謝您的回答! 我在c上有程序,就像我想要的那樣工作。我如何在C++中使用open()之類的函數? – fedden 2014-08-28 11:50:05
@fedden就像你在C使用他們一樣。 – 2014-08-28 11:54:39
謝謝,所有的工作。在C++中需要包含一些不同的庫:)) – fedden 2014-08-28 12:25:48