【网络编程】求助
服务端程序:程序代码:
#include<sys/socket.h> #include<errno.h> #include<netinet/in.h> #include<unistd.h> #include<stdio.h> #include<sys/wait.h> #include<signal.h> #include<string.h> #define MAXLEN 1000 void sig_cld(int sig) { pid_t pid; while( (pid = waitpid(-1, NULL, WNOHANG) )> 0) printf("process %d has exited\n", pid); } int main(int argc, char **argv) { int listenfd; if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) fputs("socket failed", stderr); struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(6014); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); bind(listenfd,(struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listenfd, 11); signal(SIGCHLD, sig_cld); while(1) { int connfd; char recvbuff[MAXLEN], sendbuff[MAXLEN]; if( (connfd = accept(listenfd, NULL, NULL)) < 0){ if(errno == EINTR) continue; else fputs("accept Error", stderr); } pid_t pid; if( (pid = fork() )== 0){ close(listenfd); while(read(connfd, recvbuff, MAXLEN) > 0){ int a,b; sscanf(recvbuff, "%d%d", &a, &b); sprintf(sendbuff, "%d", a+b); if( write(connfd, sendbuff, strlen(sendbuff)) < 0) fputs("Write Error", stderr); } return 0; //为什么去掉这行 当关掉客户端时 电脑就会卡死啊? 谁做到么 } close(connfd); } return 0; }
客户端程序:
程序代码:
#include<netinet/in.h> #include<sys/socket.h> #include<stdio.h> #include<string.h> #define MAXLEN 1000 int main(int argc, char *argv[]) { if(argc != 2) fputs("Input Error", stderr); int sockfd[10], i; struct sockaddr_in clientaddr; for( i=0; i<10; ++i){ if((sockfd[i] = socket(AF_INET, SOCK_STREAM, 0)) < 0) fputs("socket failed", stderr); bzero(&clientaddr,sizeof(clientaddr)); clientaddr.sin_family = AF_INET; clientaddr.sin_port = htons(6014); if( inet_pton(AF_INET, argv[1], &clientaddr.sin_addr) <= 0) fputs("inet_pton Error", stderr); if(connect(sockfd[i], (struct sockaddr *)&clientaddr, sizeof(clientaddr)) < 0) fputs("Connect error", stderr); } char recv[MAXLEN],sendbuff[MAXLEN]; while( fgets(sendbuff, MAXLEN, stdin) ){ if(write(sockfd[1], sendbuff, strlen(sendbuff)) < 0) fputs("write Error", stderr); if( read(sockfd[1], recv, MAXLEN) > 0 ){ fputs(recv, stdout); fputs("\n", stdout); } } return 0; }
为什么去掉服务端那行return 语句 在关闭客户端时 电脑会卡死啊? 求解啊