3 This file is part of libmspio
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
12 #include <msp/strings/formatter.h>
23 string name=format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this);
24 handle[0]=CreateNamedPipe(name.c_str(), PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, 0);
25 if(handle[0]==INVALID_HANDLE_VALUE)
26 throw SystemError("Unable to create pipe", GetLastError());
28 handle[1]=CreateFile(name.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
29 if(handle[1]==INVALID_HANDLE_VALUE)
31 unsigned err=GetLastError();
32 CloseHandle(handle[0]);
33 throw SystemError("Unable to create pipe", err);
37 event=CreateEvent(0, true, false, 0);
39 buffer=new char[buf_size];
44 throw SystemError("Unable to create pipe", errno);
50 void Pipe::set_block(bool b)
52 mode=(mode&~M_NONBLOCK);
54 mode=(mode|M_NONBLOCK);
57 int flags=fcntl(handle[0], F_GETFD);
58 fcntl(handle[0], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
59 flags=fcntl(handle[1], F_GETFD);
60 fcntl(handle[1], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
68 signal_flush_required.emit();
70 CloseHandle(handle[0]);
71 CloseHandle(handle[1]);
79 Handle Pipe::get_event_handle()
82 if(!overlapped && !buf_avail)
84 overlapped=new OVERLAPPED;
85 memset(overlapped, 0, sizeof(OVERLAPPED));
86 overlapped->hEvent=event;
90 if(!ReadFile(handle[0], buffer, buf_size, &ret, overlapped))
92 unsigned err=GetLastError();
93 if(err!=ERROR_IO_PENDING)
94 throw SystemError("Failed to start an overlapped read", err);
116 unsigned Pipe::do_write(const char *buf, unsigned size)
123 if(!WriteFile(handle[1], buf, size, &ret, 0))
124 throw SystemError("Writing to pipe failed", GetLastError());
126 int ret=::write(handle[1], buf, size);
132 throw SystemError("Writing to pipe failed", errno);
139 unsigned Pipe::do_read(char *buf, unsigned size)
145 // Initiate overlapped read if needed
151 if(!GetOverlappedResult(handle[0], overlapped, &ret, !buf_avail))
152 throw SystemError("Reading from pipe failed", GetLastError());
161 unsigned ret=min(buf_avail, size);
162 memcpy(buf, buf_next, ret);
166 // Initiate another overlapped read in case someone is polling us
169 int ret=::read(handle[0], buf, size);
175 throw SystemError("Reading from pipe failed", errno);
182 signal_end_of_file.emit();