C
chsalvia
I'm trying to implement a simple poll loop which asynchronously
fetches a list of URLs. Since I'm used to working with multiple
threads, I have little experience using single-threaded IO
multiplexing. I wrote a small program to try to get it to work, but
I'm having difficulty.
I connect to a bunch of non-blocking sockets, then poll them for
activity. On POLLOUT, I send an HTTP request. On POLLIN, I recv
incoming data. But the loop doesn't work. The POLLOUT even occurs
over and over again, on each socket, and POLLIN never occurs.
pollfd* pfd = (pollfd*) malloc(nsock * sizeof(pollfd));
for (int i = 0; i < nsock; ++i) {
pfd.fd = sock;
pfd.events = POLLOUT | POLLIN;
pfd.revents = 0;
}
for (int i = 0; i < nsock; ++i) {
connect(sock, (sockaddr*) &m_addr, sizeof(m_addr));
}
dbuffer buffer;
int timeout = -1;
cout << "Polling..." << endl;
for(; {
if (poll(pfd, nsock, timeout) > 0) {
for (int i = 0; i < nsock; ++i) {
if (pfd.revents & POLLOUT) {
send(sock, request, request_length, 0);
}
if (pfd.revents & POLLIN) {
cout << "Found POLL IN EVENT" << endl;
int status;
do {
if (status = buffer.recv(sock, buf, maxrecv, 0) {
if (errno != EWOULDBLOCK) break;
}
} while (status != 0);
}
}
}
else {
if (errno == EINTR) continue;
perror("poll()");
}
}
fetches a list of URLs. Since I'm used to working with multiple
threads, I have little experience using single-threaded IO
multiplexing. I wrote a small program to try to get it to work, but
I'm having difficulty.
I connect to a bunch of non-blocking sockets, then poll them for
activity. On POLLOUT, I send an HTTP request. On POLLIN, I recv
incoming data. But the loop doesn't work. The POLLOUT even occurs
over and over again, on each socket, and POLLIN never occurs.
pollfd* pfd = (pollfd*) malloc(nsock * sizeof(pollfd));
for (int i = 0; i < nsock; ++i) {
pfd.fd = sock;
pfd.events = POLLOUT | POLLIN;
pfd.revents = 0;
}
for (int i = 0; i < nsock; ++i) {
connect(sock, (sockaddr*) &m_addr, sizeof(m_addr));
}
dbuffer buffer;
int timeout = -1;
cout << "Polling..." << endl;
for(; {
if (poll(pfd, nsock, timeout) > 0) {
for (int i = 0; i < nsock; ++i) {
if (pfd.revents & POLLOUT) {
send(sock, request, request_length, 0);
}
if (pfd.revents & POLLIN) {
cout << "Found POLL IN EVENT" << endl;
int status;
do {
if (status = buffer.recv(sock, buf, maxrecv, 0) {
if (errno != EWOULDBLOCK) break;
}
} while (status != 0);
}
}
}
else {
if (errno == EINTR) continue;
perror("poll()");
}
}