Skip to content

Commit

Permalink
Add UnixSocketChannel.pair() to create a linked pair of unix sockets …
Browse files Browse the repository at this point in the history
…(ie. socketpair(2))
  • Loading branch information
vp-of-awesome committed Nov 12, 2009
1 parent 4c8b2c6 commit 876339b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/com/kenai/jnr/unixsocket/Native.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public static interface LibC {
int connect(int s, @In @Transient SockAddrUnix name, int namelen);
int getsockname(int fd, @Out SockAddrUnix addr, @In @Out IntByReference len);
int getpeername(int fd, @Out SockAddrUnix addr, @In @Out IntByReference len);
int socketpair(int domain, int type, int protocol, @Out int[] sv);
int fcntl(int fd, int cmd, int data);
String strerror(int error);
}
Expand All @@ -64,6 +65,13 @@ static int socket(ProtocolFamily domain, Sock type, int protocol) throws IOExcep
return fd;
}

static int socketpair(ProtocolFamily domain, Sock type, int protocol, int[] sv) throws IOException {
if (libsocket().socketpair(domain.value(), type.value(), protocol, sv) < 0) {
throw new IOException("socketpair(2) failed " + Native.getLastErrorString());
}
return 0;
}

static int listen(int fd, int backlog) {
return libsocket().listen(fd, backlog);
}
Expand Down
9 changes: 9 additions & 0 deletions src/com/kenai/jnr/unixsocket/UnixSocketChannel.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ public static final UnixSocketChannel open(UnixSocketAddress remote) throws IOEx
return channel;
}

public static final UnixSocketChannel[] pair() throws IOException {
int[] sockets = { -1, -1 };
Native.socketpair(ProtocolFamily.PF_UNIX, Sock.SOCK_STREAM, 0, sockets);
return new UnixSocketChannel[] {
new UnixSocketChannel(sockets[0], SelectionKey.OP_READ | SelectionKey.OP_WRITE),
new UnixSocketChannel(sockets[1], SelectionKey.OP_READ | SelectionKey.OP_WRITE)
};
}

private UnixSocketChannel() throws IOException {
super(Native.socket(ProtocolFamily.PF_UNIX, Sock.SOCK_STREAM, 0),
SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE);
Expand Down

0 comments on commit 876339b

Please sign in to comment.