Using gcc 4.4.3 on Linux 2.6.32, I get bad_cast exceptions when connecting std::basic_ofstream to a FIFO.
Stepping though the debugger, I can see that the error is generated at various places in the standard library because the _M_codecvt member of the stream or filebuf object is NULL. Exactly where it happens depends on the order of operations, but it appears to be the same cause in each.
So am I doing something fundamentally stupid here? ofstream and ifstream work fine. Is there some reason that you shouldn't attach a stream of anything besides char to a FIFO?
Thanks in advance.
EDIT: Adding source code.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <sys/stat.h>
#include <pthread.h>
using namespace std;
//#define CHAR char
#define CHAR unsigned char
bool still_writing = true;
void* reader (void*)
{
basic_ifstream<CHAR> in ("FIFO", fstream::in);
basic_streambuf<CHAR> *stream_buffer = in.rdbuf();
bool no_reads = true;
CHAR buffer[10];
while (stream_buffer->in_avail() ||
still_writing ||
no_reads)
{
in.readsome(buffer, 10);
const int got = (int)in.gcount();
if (got > 0) {
std::cerr << "Got something!\n";
no_reads = false;
}
}
}
int main ()
{
mkfifo ("FIFO", S_IRUSR | S_IWUSR);
pthread_t reader_thread_id;
pthread_create (&reader_thread_id, NULL, reader, NULL);
basic_ofstream<CHAR> out ("FIFO");
out << (CHAR) 70;
still_writing = false;
out.flush();
pthread_join (reader_thread_id, NULL);
remove ("FIFO");
}
In this version, the exception arises from stream_buffer->in_avail()
If you swap the #define
statements, everything is fine.