Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

work with fifo in c++ ( blocking read)

Tags:

c++

c

linux

fifo

What I want to do :

1.Create and open for writing in.fifo by process1

2.Open in.fifo for reading in process2

3.Write from cin to in.fifo by process1 line

4.Read and cout line by process2

5.When input "exit" to cin (process2), it closed file in.fifo, delete it and exit

6.process2 exit, because in.fifo has no writer

In my programs process2 doesn't exit. In c it works with read,write when O_NONBLOCK is clear , but I want to do it in 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;
}

I can't find where I can read about blocking read by streams like http://linux.die.net/man/3/read about blocking read

If process2 closed if input "exit", like process1 is that a life lock ? (Is it blocking on read, or just trying and trying to read )

like image 676
fedden Avatar asked Nov 24 '25 06:11

fedden


1 Answers

There is no way to do what you want using C++ standard library, because in C++ there is no notion of processes and file sharing. You have to use OS-specific APIs, which most likely are C (like open()) but in theory they can be C++.

like image 96
Anton Savin Avatar answered Nov 25 '25 19:11

Anton Savin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!