I have a simple single process server in C. It is bound to and listens on port k, and is intended to accept only one client at a time. For that, i set the listen() backlog to 0, but i still find clients waiting in queue, and they get accept()-ed when the client started before it terminates. Why?
Secondly, i start up clients one after another as c1, c2, c3, c4; and terminate c2 before terminating c1. Client c1 can still chat with the server. Interestingly, i find that when i terminate c1, the server stops as well. (Consequently, clients c3 and c4 report a read() error.) Any idea why does the server stop?
It works fine when i terminate clients in order. If all clients are terminated in order, the server will wait to accept() a new client. Does the server "remember" the order of the clients? (Although the listen() backlog is 0? Even so, why does the server stop?)
Thirdly, i tried both cases again with the listen() backlog set to INT_MAX. The same behaviour is seen.
Here's the gist of my code:
s = socket(…);
bind(…);
listen(s, 0);
while(to_serve_or_not_to_serve) {
client = accept(s, …);
if(client<0){
perror("Client not accepted");
continue;
}
serve_this_client:
r = read(client, buffer, …);
if(r<0) {
write(client, "You're dead!~\n", 14);
close(client);
continue;
}
// process some data
w = write(client, data, …);
if(w<0) {
write(client, "Your dead ペン!~\n", 15);
close(client);
continue;
}
goto serve_this_client;
}
close(s);
[Let me know if you need more details.]