17 #include <sys/socket.h>
25 socketPath(_socketPath)
31 openedAsReader = !sender;
32 struct sockaddr_un addr;
33 if ((reader_fd = ::socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
38 memset(&addr, 0,
sizeof(addr));
39 addr.sun_family = AF_UNIX;
41 if (socketPath.empty()) {
42 *addr.sun_path =
'\0';
43 strncpy(addr.sun_path + 1, socketPath.c_str() + 1,
sizeof(addr.sun_path) - 2);
45 strncpy(addr.sun_path, socketPath.c_str(),
sizeof(addr.sun_path) - 1);
47 ::unlink(socketPath.c_str());
54 while (attempts < maxAttempts) {
55 int result = ::connect(reader_fd,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr));
63 if (attempts >= maxAttempts) {
68 if (::bind(reader_fd,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr)) == -1) {
74 if (::listen(reader_fd, 2) == -1) {
78 struct sockaddr_un remote;
79 uint lenRemote =
sizeof(remote);
81 if ((sender_fd = ::accept(reader_fd,
reinterpret_cast<struct sockaddr*
>(&remote), &lenRemote)) == -1) {
112 return remoteAddress;
117 localAddress = _localAddress;
122 remoteAddress = _remoteAddress;
137 ::shutdown(sender_fd, SHUT_RDWR);
143 ::shutdown(reader_fd, SHUT_RDWR);
148 ::unlink(socketPath.c_str());
154 if (closed || !happy) {
158 result =
::read(openedAsReader ? sender_fd : reader_fd, b.
get(), b.
length());
159 if (closed || result == 0) {
176 int writtenMem =
::write(openedAsReader ? sender_fd : reader_fd, b.
get(), b.
length());
177 if (writtenMem < 0) {
179 if (errno != ETIMEDOUT) {
const yarp::os::LogComponent & UNIXSOCK_CARRIER()
bool isOk() const override
Check if the stream is ok or in an error state.
OutputStream & getOutputStream() override
Get an OutputStream to write to.
InputStream & getInputStream() override
Get an InputStream to read from.
void beginPacket() override
Mark the beginning of a logical packet.
void interrupt() override
Interrupt the stream.
bool open(bool sender=false)
const yarp::os::Contact & getRemoteAddress() const override
Get the address of the remote side of the stream.
UnixSockTwoWayStream(const std::string &_socketPath="")
void reset() override
Reset the stream.
~UnixSockTwoWayStream() override
void close() override
Terminate the stream.
void setLocalAddress(yarp::os::Contact &_localAddress)
void endPacket() override
Mark the end of a logical packet (see beginPacket).
void write(const yarp::os::Bytes &b) override
Write a block of bytes to the stream.
void setRemoteAddress(yarp::os::Contact &_remoteAddress)
const yarp::os::Contact & getLocalAddress() const override
Get the address of the local side of the stream.
A simple abstraction for a block of bytes.
Simple specification of the minimum functions needed from output streams.
static void delaySystem(double seconds)
#define yCError(component,...)
#define yCDebug(component,...)
An interface to the operating system, including Port based communication.