]> git.tdb.fi Git - libs/core.git/blob - source/io/pipe.cpp
Remove signal_closed now that closing is only done in the destructor
[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, FILE_FLAG_OVERLAPPED, 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         set_events(P_NONE);
46
47         signal_flush_required.emit();
48         sys_close(handle[0]);
49         sys_close(handle[1]);
50 }
51
52 void Pipe::set_block(bool b)
53 {
54         mode = (mode&~M_NONBLOCK);
55         if(b)
56                 mode = (mode|M_NONBLOCK);
57
58 #ifndef WIN32
59         int flags = fcntl(*handle[0], F_GETFD);
60         fcntl(*handle[0], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
61         flags = fcntl(*handle[1], F_GETFD);
62         fcntl(*handle[1], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
63 #endif
64 }
65
66 unsigned Pipe::do_write(const char *buf, unsigned size)
67 {
68         if(size==0)
69                 return 0;
70
71         return sys_write(handle[1], buf, size);
72 }
73
74 unsigned Pipe::do_read(char *buf, unsigned size)
75 {
76         if(size==0)
77                 return 0;
78
79         unsigned ret = reader.read(buf, size);
80         if(ret==0)
81                 set_eof();
82
83         return ret;
84 }
85
86 } // namespace IO
87 } // namespace Msp