2 /* $Id: pipe.cpp,v 1.3 2005-11-07 22:43:17 adam Exp $
3 Copyright (c) 2005, Index Data.
17 #include <netinet/in.h>
19 #include <arpa/inet.h>
20 #include <netinet/tcp.h>
26 #include <sys/socket.h>
29 #include <sys/select.h>
32 #include <boost/thread/thread.hpp>
33 #include <boost/thread/mutex.hpp>
34 #include <boost/thread/condition.hpp>
40 #include <yaz++/socket-observer.h>
46 class Pipe::Rep : public boost::noncopyable {
58 void Pipe::Rep::close(int &fd)
72 m_fd[0] = m_fd[1] = -1;
76 bool Pipe::Rep::nonblock(int s)
79 unsigned long tru = 1;
80 if (ioctlsocket(s, FIONBIO, &tru) < 0)
83 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
86 signal (SIGPIPE, SIG_IGN);
92 Pipe::Pipe(int port_to_use) : m_p(new Rep)
96 // create server socket
97 m_p->m_socket = socket(AF_INET, SOCK_STREAM, 0);
98 if (m_p->m_socket < 0)
99 throw Pipe::Error("could not create socket");
101 unsigned long one = 1;
102 if (setsockopt(m_p->m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)
103 &one, sizeof(one)) < 0)
104 throw Pipe::Error("setsockopt error");
106 // bind server socket
107 struct sockaddr_in add;
108 add.sin_family = AF_INET;
109 add.sin_port = htons(port_to_use);
110 add.sin_addr.s_addr = INADDR_ANY;
111 struct sockaddr *addr = ( struct sockaddr *) &add;
113 if (bind(m_p->m_socket, addr, sizeof(struct sockaddr_in)))
114 throw Pipe::Error("could not bind on socket");
116 if (listen(m_p->m_socket, 3) < 0)
117 throw Pipe::Error("could not listen on socket");
121 tmpadd = (unsigned) inet_addr("127.0.0.1");
123 memcpy(&add.sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
125 throw Pipe::Error("inet_addr failed");
127 m_p->m_fd[1] = socket(AF_INET, SOCK_STREAM, 0);
128 if (m_p->m_fd[1] < 0)
129 throw Pipe::Error("could not create socket");
131 m_p->nonblock(m_p->m_fd[1]);
133 if (connect(m_p->m_fd[1], addr, sizeof(*addr)) < 0)
136 if (WSAGetLastError() != WSAEWOULDBLOCK)
137 throw Pipe::Error("could not connect to socket");
139 if (errno != EINPROGRESS)
140 throw Pipe::Error("could not connect to socket");
145 struct sockaddr caddr;
147 int caddr_len = sizeof(caddr);
149 socklen_t caddr_len = sizeof(caddr);
151 m_p->m_fd[0] = accept(m_p->m_socket, &caddr, &caddr_len);
152 if (m_p->m_fd[0] < 0)
153 throw Pipe::Error("could not accept on socket");
158 FD_SET(m_p->m_fd[1], &write_set);
159 int r = select(m_p->m_fd[1]+1, 0, &write_set, 0, 0);
161 throw Pipe::Error("could not complete connect");
163 m_p->close(m_p->m_socket);
175 m_p->close(m_p->m_fd[0]);
176 m_p->close(m_p->m_fd[1]);
177 m_p->close(m_p->m_socket);
180 int &Pipe::read_fd() const
185 int &Pipe::write_fd() const
193 * indent-tabs-mode: nil
194 * c-file-style: "stroustrup"
196 * vim: shiftwidth=4 tabstop=8 expandtab