我正在尝试套接字编程和服务器代码:
while(1) {
sin_size = sizeof (their_addr);
new_fd = accept(sockfd,(struct sockaddr *)&their_addr, &sin_size);
if(new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr*)&their_addr),s,sizeof(s));
cout<<"got connection from" << s << endl;
if((pid = fork()) == 0){//child
close(sockfd);
if(send(new_fd,"hello world!",12,0) == -1) {
perror("send");
close(new_fd);
exit(0);
}
char buf[50];
int numbytes;
if((numbytes = recv(new_fd,&buf,50,0)) == -1) {
perror("receive");
close(new_fd);
exit(0);
}
buf[numbytes] = '\0';
cout<<"numbytes" << numbytes <<endl;
cout<<"server received " << buf <<endl;
}
close(new_fd);
}
这段代码给了我一个错误的文件描述符,但是当我评论关闭(sockfd)时,代码运行良好。由于我正在分叉到一个新的子进程并关闭侦听端口,为什么我得到一个错误的文件描述符?有什么我在这里想念的吗。