views:

1158

answers:

3

I open a FIFO file as ifstream. As soon as the object is created the thread is blocked until I send something into the FIFO (which is OK for me). I then call getline() to get the data from stream.

How do I read-block the thread again until more data is written into FIFO file?

Thanks

+1  A: 

The getline function provided by <string> returns a reference to the stream object. You can test this object for "goodness" to see if it's still open or if an error has occurred:

std::ifstream fifo;
std::string   line;

/* code to open your FIFO */

while (std::getline(fifo, line))
{
    /* do stuff with line */
}

When the FIFO closes, the while test will return false to exit the loop. Every loop iteration will effectively read-block the thread until more data is ready.

Kristo
A: 

I use the stream as follows:

ifstream _FifoInStream(_FifoInFileName.c_str(), ifstream::in);

string CmdLine;

while (std::getline(_FifoInStream, CmdLine)) {
    cout << CmdLine << endl;
}

I'm blocked only when I initialize _FifoInStream variable i.e. open the stream. After I send data into FIFO I fall through the while block. What I need is to read from FIFO indefinitely each time being blocked on read.

Jack
Do you close FIFO after sending data? E.g., if you use echo command to send data, echo opens FIFO, sends data and then closes it.
Arkadiy
I do. Echo is exactly what I use.
Jack
+1  A: 

I haven't tested this code but I'm wondering if the FIFO is simply setting the EOF bit when you read all available data. In that case, you might be able to do this:

std::ifstream fifo;
std::string   line;
bool          done = false;

/* code to open your FIFO */

while (!done)
{
    while (std::getline(fifo, line))
    {
        /* do stuff with line */
    }
    if (fifo.eof())
    {
        fifo.reset();  // Clear the EOF bit to enable further reading
    }
    else
    {
        done = true;
    }
}

If you read off the end of the FIFO, reset and wait for further data. If an error occurred, you're done. I got the idea for this from this website. You might have to also close and reopen the FIFO in the same block where you do the reset.

Kristo