I want to write a multi clients socket program,
but I get Bad file descriptor when the stage of accept.
How can I correct my code? Thanks!
Here is my code
http://codepad.org/q0N1jTgz
Thanks!
Here is my part of code!
while(1)
{
struct sockaddr_in client_addr;
int addrlen = sizeof(client_addr);
/*Accept*/
if(clientfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&addrlen) < 0)
{
perror("Accpet Error");
close(sockfd);
exit(-1);
}
/*Fork process*/
if(child = fork() < 0)
{
perror("Fork Error");
close(sockfd);
exit(-1);
}
else if(child == 0)
{
int my_client = clientfd;
close(sockfd);
send(my_client, welcome, sizeof(welcome), 0);
while ((res = recv(my_client, buffer1, sizeof(buffer1), 0)) > 0)
{
string command(buffer1);
cout << "receive from client:" << command << ", " << res << " bytes\n";
memset(buffer1, '\0', sizeof(buffer1));
}
}
close(clientfd);
}
there are a few bugs in your code first you need to use parentheses around the assignments for
childandclientfd.line
68should be changed toand line
76should beadditionally you must
returnorexit()from the forked process since you have already closed the listening socket.so add
exit(0);orreturn 0;after line94I highly recommend you compile your code with warnings enabled, to catch the assignment problems early. e.g use the
-Walland-Wextraflags if you are usinggccorg++