AetX
AetX

Reputation: 213

How to prevent program being blocked by socket listen()

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.

Upvotes: 0

Views: 437

Answers (1)

Joshua
Joshua

Reputation: 43327

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().

Upvotes: 2

Related Questions