0

I'm writing a server program, at the initialization, I want to bind() and listen() at certain ip/port. But then the whole program is blocked by listen(). Is there any way can make the program check for new incoming connection every, say, 5ms?

My code is currently like this:

int main(){
    initialize();
    do_something();

    return 0;
}

In initialize(), socket is set up:

void initialize(){
    sockfd = sock_create_bind(ip_addr[nodeid], port_addr[nodeid]);
    listen(sockfd, 5);
    peer_sockfd = accept(sockfd, (struct sockaddr *)&peer_addr, &peer_addr_len);
}

But initialize() never returns, and do_something() never get called. So I'm wondering is there anyway to prevent this blocking? Thanks.

AetX
  • 193
  • 6

1 Answers1

2

You're blocking here

peer_sockfd = accept(sockfd, (struct sockaddr *)&peer_addr, &peer_addr_len);

To avoid blocking you can use select

fd_set fds;
FD_ZERO(fds);
FD_SET(sockfd, fds);
struct timeval tv = { 0, 0 };
select(sockfd + 1, &fds, NULL, NULL, &tf);
if (FD_ISSET(socktf, fds)) {
    peer_sockfd = accept(sockfd, (struct sockaddr *)&peer_addr, &peer_addr_len);
}

To decide the interval to check for, write your code so this is called at the appropriate interval.

You'll need to do a similar thing for read() and write() on peer_sockfd. If you assume that sockfd isn't from a hostile host OS, you can get away with only checking on read().

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • `write()` will also block if the remote peer isn't processing the incoming data fast enough -- that might happen if the remote program has (for some reason) stopped calling `recv()` on a timely basis, or (more commonly) if the network between your program and the remote peer is flaky and dropping packets, causing the TCP transmission rate to become slower than the rate at which your program is `send()`-ing data. – Jeremy Friesner Sep 06 '19 at 19:26
  • @JeremyFriesner: Correct. In my experience this rarely is important to most cases. It's the `read()` or `accept()` blocked for an hour that's bad. – Joshua Sep 06 '19 at 19:28
  • An easy way to observe `write()` getting blocked is to pull the ethernet cable out of its socket and leave it disconnected for 15-30 seconds, while your program is trying to send a non-trivial amount of TCP data to some destination elsewhere on the network. – Jeremy Friesner Sep 08 '19 at 01:44