xdrpp
RFC4506 XDR compiler and message library
socket_unix.cc
1 
2 #include <cstring>
3 #include <iostream>
4 #include <sstream>
5 #include <vector>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <netinet/in.h>
9 #include <xdrpp/socket.h>
10 #include <xdrpp/srpc.h>
11 #include <xdrpp/rpcb_prot.hh>
12 
13 namespace xdr {
14 
15 using std::string;
16 
17 bool
19 {
20  int err = errno;
21  return err == EAGAIN || err == EWOULDBLOCK || err == EINTR;
22 }
23 
24 const char *
26 {
27  return std::strerror(errno);
28 }
29 
30 void
31 throw_sockerr(const char *msg)
32 {
33  throw std::system_error(errno, std::system_category(), msg);
34 }
35 
36 ssize_t
37 read(sock_t s, void *buf, std::size_t count)
38 {
39  return ::read(s.fd(), buf, count);
40 }
41 
42 ssize_t
43 write(sock_t s, const void *buf, std::size_t count)
44 {
45  return ::write(s.fd(), buf, count);
46 }
47 
48 ssize_t
49 readv(sock_t s, const struct iovec *iov, int iovcnt)
50 {
51  return ::readv(s.fd(), iov, iovcnt);
52 }
53 
54 ssize_t writev(sock_t s, const struct iovec *iov, int iovcnt)
55 {
56  return ::writev(s.fd(), iov, iovcnt);
57 }
58 
59 void
60 close(sock_t s)
61 {
62  while (::close(s.fd()) == -1)
63  if (!sock_eagain()) { // EINTR possible
64  std::cerr << "close: " << sock_errmsg() << std::endl;
65  return;
66  }
67 }
68 
69 void
71 {
72  int n;
73  if ((n = fcntl (s.fd_, F_GETFL)) == -1
74  || fcntl (s.fd_, F_SETFL, n | O_NONBLOCK) == -1)
75  throw_sockerr("O_NONBLOCK");
76 }
77 
78 void
80 {
81  int n;
82  if ((n = fcntl(s.fd_, F_GETFD)) == -1
83  || fcntl(s.fd_, F_SETFD, n | FD_CLOEXEC) == -1)
84  throw_sockerr("F_SETFD");
85 }
86 
87 
88 void
90 {
91  int fds[2];
92  if (pipe(fds) == -1)
93  throw std::system_error(errno, std::system_category(), "pipe");
94  ss[0] = sock_t(fds[0]);
95  ss[1] = sock_t(fds[1]);
96 }
97 
98 }
void throw_sockerr(const char *)
Throw a system_error exception for the last socket error.
Definition: socket_unix.cc:31
Most of the xdrpp library is encapsulated in the xdr namespace.
Definition: arpc.cc:4
bool sock_eagain()
Returns true if the most recent (socket) error is a temporary error, such as EAGAIN, EWOULDBLOCK, or EINTR.
Definition: socket_unix.cc:18
void set_nonblock(sock_t s)
Set the O_NONBLOCK flag on a socket.
Definition: socket_unix.cc:70
Simple synchronous RPC functions.
const char * sock_errmsg()
Last socket error message (strerror(errno) on POSIX).
Definition: socket_unix.cc:25
Abstract away the type of a socket (for windows).
Definition: socket.h:28
void create_selfpipe(sock_t ss[2])
Create a socket (or pipe on unix, where both are file descriptors) that is connected to itself...
Definition: socket_unix.cc:89
Simplified support for creating sockets.
void set_close_on_exec(sock_t s)
Set the close-on-exec flag of a file descriptor.
Definition: socket_unix.cc:79