namespace Msp {
namespace IO {
-struct Pipe::Private
-{
-#ifdef WIN32
- OVERLAPPED *overlapped;
- Handle event;
- unsigned buf_size;
- char *buffer;
- unsigned buf_avail;
- char *buf_next;
-#endif
-};
-
-
Pipe::Pipe():
- priv(0)
+ reader(handle[0], 1024)
{
#ifdef WIN32
string name = format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this);
CloseHandle(*handle[0]);
throw system_error(format("CreateFile(%s)", name), err);
}
-
- priv = new Private;
- priv->overlapped = 0;
- *priv->event = CreateEvent(0, true, false, 0);
- priv->buf_size = 1024;
- priv->buffer = new char[priv->buf_size];
- priv->buf_avail = 0;
- priv->buf_next = priv->buffer;
#else
int pipe_fd[2];
if(pipe(pipe_fd)==-1)
Pipe::~Pipe()
{
close();
-#ifdef WIN32
- CloseHandle(*priv->event);
- delete priv->buffer;
-#endif
- delete priv;
}
void Pipe::close()
if(size==0)
return 0;
-#ifdef WIN32
- // Initiate overlapped read if needed
- get_event_handle();
-
- if(priv->overlapped)
- {
- DWORD ret;
- if(!GetOverlappedResult(*handle[0], priv->overlapped, &ret, !priv->buf_avail))
- throw system_error("GetOverlappedResult");
- else
- {
- priv->buf_avail += ret;
- delete priv->overlapped;
- priv->overlapped = 0;
- }
- }
-
- unsigned ret = min(priv->buf_avail, size);
- memcpy(buf, priv->buf_next, ret);
- priv->buf_next += ret;
- priv->buf_avail -= ret;
-
- // Initiate another overlapped read in case someone is polling us
- get_event_handle();
-#else
- unsigned ret = sys_read(handle[0], buf, size);
-#endif
+ unsigned ret = reader.read(buf, size);
if(ret==0)
{
return ret;
}
-const Handle &Pipe::get_event_handle()
-{
-#ifdef WIN32
- if(!priv->overlapped && !priv->buf_avail)
- {
- priv->overlapped = new OVERLAPPED;
- memset(priv->overlapped, 0, sizeof(OVERLAPPED));
- priv->overlapped->hEvent = *priv->event;
-
- DWORD ret;
- priv->buf_next = priv->buffer;
- if(!ReadFile(*handle[0], priv->buffer, priv->buf_size, &ret, priv->overlapped))
- {
- unsigned err = GetLastError();
- if(err!=ERROR_IO_PENDING)
- throw system_error("ReadFile");
- }
- else
- {
- priv->buf_avail = ret;
- delete priv->overlapped;
- priv->overlapped = 0;
- SetEvent(*priv->event);
- }
- }
-
- return priv->event;
-#else
- return handle[0];
-#endif
-}
-
} // namespace IO
} // namespace Msp