Sorry for pasting something as basic as this, but I don't seem to be able to figure this out. I'm using this example, pasted from an online tutorial, for a basic socket server application:
Code:
void dostuff(int);
void error(char *);
int main(int argc, char *argv[]) {
int unsigned sockfd, newsockfd, portno, clilen, pid;
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
error("ERROR on binding");
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
error("ERROR on accept");
}
pid = fork();
if (pid < 0) {
error("ERROR on fork");
}
if (pid == 0) {
close(sockfd);
dostuff(newsockfd);
exit(0); <------ line XXX
}
else close(newsockfd);
}
return 0; /* we never get here */
}
void error(char *msg) {
perror(msg);
exit(1);
}
void dostuff(int sock) {
int n;
char buffer[256];
bzero(buffer,256);
n = read(sock,buffer,255);
if (n < 0) {
error("ERROR reading from socket");
}
printf("Here is the message: %s\n",buffer);
n = write(sock,"I got your message",18);
if (n < 0) {
error("ERROR writing to socket");
}
}
The "problem" with this code is that, when I connect to the server (I'm just telnetting to the port), after sending a message to the server, the client just shuts down ("Connection closed by foreign host") after receiving the "I got your message" message from the server. I've tried commenting out line XXX (which reads "exit(0)", but that just results in the server returning this error:
Code:
ERROR reading from socket: Bad file descriptor
Any ideas/hints/suggestions?