]> git.tdb.fi Git - libs/core.git/blob - source/io/unix/handle.cpp
Avoid closing handles twice
[libs/core.git] / source / io / unix / handle.cpp
1 #include <cerrno>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <msp/core/systemerror.h>
5 #include "handle.h"
6 #include "handle_private.h"
7
8 namespace Msp {
9 namespace IO {
10
11 Handle::operator const void *() const
12 {
13         return priv->handle!=-1 ? this : 0;
14 }
15
16
17 void sys_set_blocking(Handle &handle, bool b)
18 {
19         int flags = fcntl(*handle, F_GETFD);
20         fcntl(*handle, F_SETFL, (flags&~O_NONBLOCK)|(b?0:O_NONBLOCK));
21 }
22
23 unsigned sys_read(Handle &handle, char *buf, unsigned size)
24 {
25         int ret = read(*handle, buf, size);
26         if(ret==-1)
27         {
28                 if(errno==EAGAIN)
29                         return 0;
30                 else
31                         throw system_error("read");
32         }
33
34         return ret;
35 }
36
37 unsigned sys_write(Handle &handle, const char *buf, unsigned size)
38 {
39         int ret = write(*handle, buf, size);
40         if(ret==-1)
41         {
42                 if(errno==EAGAIN)
43                         return 0;
44                 else
45                         throw system_error("write");
46         }
47
48         return ret;
49 }
50
51 void sys_close(Handle &handle)
52 {
53         if(handle)
54         {
55                 close(*handle);
56                 *handle = INVALID_HANDLE_VALUE;
57         }
58 }
59
60 } // namespace IO
61 } // namespace Msp