I made a simple internet program for Linux and was playing with it when I realised that it takes up to 99% of
cpu resources. I believe there's something wrong with my main loop, but can't seem to fix it, even though I
gone to various measures to find the source of the problem. Tutorials on the subject suggests that my method
is already pretty efficient, though I can't be sure. Anyone has time, please look at the code attached and give
me comments please? Thanks!
Teng Junbin
void MainLoop(int sockfd) {
fd_set rea_set, err_set;
static struct timeval nulltime;
for (;;) {
// Check for incoming data and errors
FD_ZERO(&rea_set);
FD_ZERO(&err_set);
FD_SET(fileno(stdin), &rea_set);
FD_SET(sockfd, &rea_set);
FD_SET(sockfd, &err_set);
if (select(fileno(stdin) > sockfd ? fileno(stdin) + 1 : sockfd + 1, &rea_set, NULL, &err_set, &nulltime) < 0) {
puts("ERROR: Unable to pool incoming data and errors\n");
puts(CONNECTIONCLOSED);
close(sockfd);
exit(3);
}
// Check for error in connection
if (FD_ISSET(sockfd, &err_set)) {
// Disconnected
close(sockfd);
puts(CONNECTIONCLOSED);
break;
} else {
// Get server input
if (FD_ISSET(sockfd, &rea_set)) {
if (!ProcessData(sockfd)) {
// Disconnected
close(sockfd);
puts(CONNECTIONCLOSED);
break;
}
}
// Get keyboard input
if (FD_ISSET(fileno(stdin), &rea_set)) {
if (!ProcessData(fileno(stdin)) {
// IO Error
puts("ERROR: Unable to read from stdin\n\n");
close(sockfd);
exit(5);
}
}
}
}
}[QUOTE]