Add FILE_FLAG_OVERLAPPED in a couple of places
[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         signal_closed.emit();
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