]> git.tdb.fi Git - libs/core.git/blob - source/io/pipe.cpp
Disable main() on win32 in favor of WinMain
[libs/core.git] / source / io / pipe.cpp
1 #ifndef WIN32
2 #include <fcntl.h>
3 #include <errno.h>
4 #include <unistd.h>
5 #endif
6 #include <msp/core/systemerror.h>
7 #include <msp/strings/format.h>
8 #include "handle_private.h"
9 #include "pipe.h"
10
11 using namespace std;
12
13 namespace Msp {
14 namespace IO {
15
16 Pipe::Pipe():
17         reader(read_handle, 1024)
18 {
19         mode = M_RDWR;
20
21 #ifdef WIN32
22         string name = format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this);
23         *read_handle = CreateNamedPipe(name.c_str(), PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, 0);
24         if(!read_handle)
25                 throw system_error("CreateNamedPipe");
26
27         *write_handle = CreateFile(name.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
28         if(!write_handle)
29         {
30                 unsigned err = GetLastError();
31                 CloseHandle(*read_handle);
32                 throw system_error(format("CreateFile(%s)", name), err);
33         }
34 #else
35         int pipe_fd[2];
36         if(pipe(pipe_fd)==-1)
37                 throw system_error("pipe");
38
39         *read_handle = pipe_fd[0];
40         *write_handle = pipe_fd[1];
41 #endif
42
43         set_events(P_INPUT);
44 }
45
46 Pipe::~Pipe()
47 {
48         set_events(P_NONE);
49
50         signal_flush_required.emit();
51         sys_close(read_handle);
52         sys_close(write_handle);
53 }
54
55 void Pipe::set_block(bool b)
56 {
57         mode = (mode&~M_NONBLOCK);
58         if(b)
59                 mode = (mode|M_NONBLOCK);
60
61 #ifndef WIN32
62         int flags = fcntl(*read_handle, F_GETFD);
63         fcntl(*read_handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
64         flags = fcntl(*write_handle, F_GETFD);
65         fcntl(*write_handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
66 #endif
67 }
68
69 unsigned Pipe::do_write(const char *buf, unsigned size)
70 {
71         if(size==0)
72                 return 0;
73
74         return sys_write(write_handle, buf, size);
75 }
76
77 unsigned Pipe::do_read(char *buf, unsigned size)
78 {
79         if(size==0)
80                 return 0;
81
82         unsigned ret = reader.read(buf, size);
83         if(ret==0)
84                 set_eof();
85
86         return ret;
87 }
88
89 const Handle &Pipe::get_handle(Mode m)
90 {
91         if(m==M_READ)
92                 return read_handle;
93         else if(m==M_WRITE)
94                 return write_handle;
95         else
96                 throw invalid_argument("Pipe::get_handle");
97 }
98
99 } // namespace IO
100 } // namespace Msp