12f8fbd3886ea7f269b125691a19b2074ee16d11
[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 #ifdef WIN32
20         string name = format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this);
21         *read_handle = CreateNamedPipe(name.c_str(), PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, 0);
22         if(!read_handle)
23                 throw system_error("CreateNamedPipe");
24
25         *write_handle = CreateFile(name.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
26         if(!write_handle)
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         *read_handle = pipe_fd[0];
38         *write_handle = 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(read_handle);
50         sys_close(write_handle);
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(*read_handle, F_GETFD);
61         fcntl(*read_handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
62         flags = fcntl(*write_handle, F_GETFD);
63         fcntl(*write_handle, 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(write_handle, 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