在查看了 Beej 的网络编程指南之后,我尝试使用 select 而不是 fork 来重做我的 server.c。我不太确定出了什么问题;我的程序编译,但不接受连接。我知道包含 i<=fdmax 的循环运行不正常,但我不知道为什么。似乎 if 语句无法正常工作。
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/select.h>
#define Connections 5
void SignalCatcher(int signum)
{
wait3(NULL,WNOHANG, NULL);
//wait(-1);
}
int main(int argc, char**argv)
{
int listenfd,connfd,n, i;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
pid_t childpid;
char mesg[1000];
FILE *inputFile;
inputFile = fopen("movie.txt", "r");
char returnMsg[1000];
int fdmax, newfd;
fd_set readfd;
fd_set mastersocket;
FD_ZERO(&mastersocket);
FD_ZERO(&readfd);
//Creating socket number
listenfd=socket(AF_INET,SOCK_STREAM,0);
//Setting up the internet address
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(32000);
bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
//Listening for clients
listen(listenfd,1024);
FD_SET(listenfd, &mastersocket);
fdmax=listenfd;
//signal(SIGCHLD, SIG_IGN);
signal(SIGCHLD, SignalCatcher);
//Infinite loop that waits for/accepts connections.
for(;;)
{
readfd = mastersocket;
clilen=sizeof(cliaddr);
if(select(fdmax+1, &readfd, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);}
//connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
for(i=0; i<=fdmax;i++)
{
if (FD_ISSET(i, &readfd)){
if(i==listenfd){
printf("-SUCCESS\n");
clilen = sizeof cliaddr;
connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen); }
if (connfd!=-1)
{
// if ((childpid = fork()) == 0)
// {
close (listenfd);
for(;;)
{
n = recvfrom(connfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&clilen);
if (n == -1 /*&& errno == EWOULDBLOCK*/) continue;
else if(n==0) break;
//sendto(connfd,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
//write(connfd , mesg , strlen(mesg)); //both work
//write(connfd , "" , 1);
printf("-------------------------------------------------------\n");
printf("%d",listenfd);
mesg[n] = 0;
printf("Received the following:\n");
printf("%s",mesg);
printf("-------------------------------------------------------\n");
}
// }
close(connfd);
} //if connfd!=-1
}
} //for i<=fdmax
}
}