In MacOS I set up a read+write socket with O_NONBLOCK
to connect to a remote server. I use kqueue to wait for and coordinate I/O events. The call to connect()
immediately triggers EINPROGRESS
, as it should. Soon after, the connection is completed. This is confirmed by receiving data from the server.
BUT, I thought kqueue would return a kevent when the connection finally completes and becomes writable? No such event arrives. The man page for connect()
states:
[EINPROGRESS] The socket is non-blocking and the connection cannot be completed immediately. It is possible to select(2) for completion by selecting the socket for writing.
(1) Does this mean I need to use select()
instead of kqueque to receive notification of the completed connection?
(2) By the way, if I try to connect to a server where nothing is listening on the port, then kevent soon returns EOF to report there is nothing there.
(3) If I try to connect to a non-existing IP, then my kevent times out after the timeout period I have set (15 sec).
Code below. Compile, start a "server" such as nc -l 10000
, run program with or without an IP address argument, and it will connect remotely or locally, respectively.
#include <sys/event.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int fd = socket(PF_INET, SOCK_STREAM, 0);
if (fd < 0) {
perror("socket");
}
int fcntl_flags = fcntl(fd, F_GETFL);
if (fcntl_flags < 0) {
perror("fcntl");
}
fcntl_flags = fcntl(fd, F_SETFL, fcntl_flags | O_NONBLOCK);
if (fcntl_flags < 0) {
perror("fcntl");
}
struct sockaddr_in addr_in;
memset(&addr_in, 0, sizeof addr_in);
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(10000);
if (!inet_pton(AF_INET, argc > 1 ? argv[1] : "127.0.0.1", &addr_in.sin_addr)) {
perror("inet_aton");
exit(EXIT_FAILURE);
}
struct kevent change;
struct kevent event;
// Create kqueue
int kq;
if ((kq = kqueue()) < 0) {
perror("kqueue");
}
// Set read and write on socket
EV_SET(&change, fd, EVFILT_READ | EVFILT_WRITE, EV_ADD | EV_CLEAR, 0, 0, NULL);
// Put socket in kqueue, return immediately
struct timespec tmout = { 0, 0 };
int nev = kevent(kq, &change, 1, &event, 1, &tmout);
printf("Number events: %d (should be 0)\n", nev);
// Connect socket to server
if (!connect(fd, (struct sockaddr *) &addr_in, sizeof(struct sockaddr))) {
printf("Connected\n");
}
else if (errno == EINPROGRESS) {
printf("EINPROGRESS\n");
}
// Wait for connection to complete
tmout.tv_sec = 15;
nev = kevent(kq, &change, 0, &event, 1, &tmout);
if (nev) {
printf("Number events: %d, filter: %x, flags: %x, data: %ld\n", nev, event.filter, event.flags, event.data);
}
else {
printf("Timeout\n");
}
return 0;
}