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