サーバーの並行型通信について質問です。
下記ソースコードはコンパイルに成功するのですが、実行した際、
Waiting for client が表示され、そこから動きません。
この場合、どういった原因が考えられるでしょうか?
C
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4#include <unistd.h> 5#include <sys/socket.h> 6#include <netinet/in.h> 7#include <arpa/inet.h> 8#include <sys/types.h> 9#include <pthread.h> 10 11#define BUFSIZE 1024 12#define LISTENQ 1024 13 14void *thread(void *arg); 15 16struct ThreadArgs { 17 int sock; 18 int cnt; 19 struct sockaddr_in sa; 20}; 21 22int main(int argc, char *argv[]) 23{ 24 int listen_sock,comm_sock,sa_len,cnt; 25 struct sockaddr_in sa,new_sa; 26 pthread_t thread_id; 27 struct ThreadArgs *args; 28 29 listen_sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP); 30 31 memset(&sa,0,sizeof(sa)); 32 sa.sin_family = AF_INET; 33 sa.sin_port = htons(49152); 34 sa.sin_addr.s_addr = htonl(INADDR_ANY); 35 36 if(bind(listen_sock,(struct sockaddr *)&sa,sizeof(sa)) < 0){ 37 fprintf(stderr,"bind()failure\n"); 38 exit(1); 39} 40 41 if(listen(listen_sock,LISTENQ) < 0){ 42 fprintf(stderr,"listen()failure\n"); 43 exit(1); 44} 45 46 47cnt=0; 48while(1){ 49 printf("Waiting for a client\n"); 50 sa_len = sizeof(new_sa); 51 if((comm_sock = accept(listen_sock,(struct sockaddr *)&new_sa,&sa_len)) < 0){ 52 fprintf(stderr,"accept() failure\n"); 53 exit(1); 54 } 55 ++cnt; 56 //1.引数用の構造体メモリを確保する 57 args = (struct ThreadArgs *)malloc(sizeof(struct ThreadArgs)); 58 if(args == NULL){ 59 fprintf(stderr,"malloc() failure\n"); 60 exit(1); 61 } 62 //2 63 args->sock = comm_sock; 64 args->cnt = cnt; 65 args->sa = new_sa; 66 67 //3 68 if(pthread_create(&thread_id,NULL,(void*)thread, (void*)args)!=0){ 69 fprintf(stderr, "pthread_create() failure\n"); 70 exit(1); 71 } 72 } 73 return 0; 74} 75 76void *thread(void *arg) 77{ 78 int sock,cnt,n,msg_len; 79 struct sockaddr_in sa; 80 char buf[BUFSIZE]; 81 82 pthread_detach(pthread_self()); 83 84 //4 85 sock = ((struct ThreadArgs *)arg)->sock; 86 cnt = ((struct ThreadArgs *)arg)->cnt; 87 sa = ((struct ThreadArgs *)arg)->sa; 88 89 90 printf("Client %d (%s) connected\n", cnt, inet_ntoa(sa.sin_addr)); 91 92 93 while(1){ 94 if((n =recv(sock,buf,sizeof(buf),0)) > 0){ 95 buf[n] = '\0'; 96 msg_len = strlen(buf); 97 printf("Client &d: %s\n" , cnt,buf); 98 if(send(sock,buf,msg_len,0)!=msg_len){ 99 fprintf(stderr,"send() failure\n"); 100 free(arg); 101 return; 102 } 103 }else{ 104 break; 105 } 106 } 107 close(sock); 108 109 printf("Client %d disconnected\n",cnt); 110 111 free(arg); 112return; 113} 114