Reputation: 590
So, I am new to socket programming in C and am using the select
function to communicate with multiple clients on a server. The server essentially just echos a buffer back to a client based on a requirest. I have used Beej's guide to network programming as the model for my server. What is not clear to me is whether I am exiting the server properly when a command is sent to exit. The code for handling the select
function looks like:
for (;;)
{
read_fds = master; // Copy the master fds to the basic read...
// Check to see if any flags have been set for reading
if (select(fdmax + 1, &read_fds, NULL, NULL, NULL) == -1)
{
perror("select");
exit(4);
}
for (i = 0; i <= fdmax; i++)
{
if (FD_ISSET(i, &read_fds))
{
if (i == listener)
{ // need to add new connnection here
addrlen = sizeof remote_addr;
newfd = accept(listener, (struct sockaddr *)&remote_addr, &addrlen);
if (newfd == -1)
{
perror("accept");
}
else
{
FD_SET(newfd, &master);
if (newfd > fdmax)
{
fdmax = newfd;
}
}
} // end add new listener
else
{
/*if (i == 0)
{
printf("Input received from stdin\n");
continue;
} */
// handle data from existing client
if ((nbytes = recv(i, input_buffer, sizeof input_buffer, 0)) <= 0)
{ // Remove connection if there is a hangup...
if (nbytes == 0)
{
printf("selectserver: socket%d hung up\n", i);
}
else
{
perror("recv");
}
close(i);
FD_CLR(i, &master);
} // no bytes error or port closed - remove from fdset
else
{
if (strchr(input_buffer,'\r') == NULL){
printf("we have a problem\n");
}
if (strcmp(input_buffer, "exit")){
printf("Exit requested...\n");
close(listener);
exit(0);
}
for (j = 0; j <= fdmax; j++)
{
if (FD_ISSET(j, &master))
{
if (j != listener && j != 0)
{
if (send(j, input_buffer, nbytes, 0) == -1)
{
error_msg = strerror(errno);
printf("%s\n", error_msg);
//perror("send");
}
}
}
}
}
}
}
}
}
and the code I am specifically concerned about is
if (strcmp(input_buffer, "exit")){
printf("Exit requested...\n");
close(listener);
exit(0);
}
where listener
is the file descriptor for the listening socket. Is this the correct way of exiting this loop or is there a better way to handle this?
Upvotes: 0
Views: 396
Reputation: 225437
What you are doing is correct.
The proper way to close a socket, whether it is a connected socket or a listening socket, is with close
.
Upvotes: 1