]> git.tdb.fi Git - libs/core.git/blob - source/io/pipe.cpp
Add missing headers
[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(handle[0], 1024)
18 {
19 #ifdef WIN32
20         string name = format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this);
21         *handle[0] = CreateNamedPipe(name.c_str(), PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, 0);
22         if(!handle[0])
23                 throw system_error("CreateNamedPipe");
24
25         *handle[1] = CreateFile(name.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
26         if(!handle[1])
27         {
28                 unsigned err = GetLastError();
29                 CloseHandle(*handle[0]);
30                 throw system_error(format("CreateFile(%s)", name), err);
31         }
32 #else
33         int pipe_fd[2];
34         if(pipe(pipe_fd)==-1)
35                 throw system_error("pipe");
36
37         *handle[0] = pipe_fd[0];
38         *handle[1] = pipe_fd[1];
39 #endif
40
41         set_events(P_INPUT);
42 }
43
44 Pipe::~Pipe()
45 {
46         set_events(P_NONE);
47
48         signal_flush_required.emit();
49         sys_close(handle[0]);
50         sys_close(handle[1]);
51 }
52
53 void Pipe::set_block(bool b)
54 {
55         mode = (mode&~M_NONBLOCK);
56         if(b)
57                 mode = (mode|M_NONBLOCK);
58
59 #ifndef WIN32
60         int flags = fcntl(*handle[0], F_GETFD);
61         fcntl(*handle[0], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
62         flags = fcntl(*handle[1], F_GETFD);
63         fcntl(*handle[1], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
64 #endif
65 }
66
67 unsigned Pipe::do_write(const char *buf, unsigned size)
68 {
69         if(size==0)
70                 return 0;
71
72         return sys_write(handle[1], buf, size);
73 }
74
75 unsigned Pipe::do_read(char *buf, unsigned size)
76 {
77         if(size==0)
78                 return 0;
79
80         unsigned ret = reader.read(buf, size);
81         if(ret==0)
82                 set_eof();
83
84         return ret;
85 }
86
87 } // namespace IO
88 } // namespace Msp