2013-05-04 74 views
-1

我正在尝试创建一个将侦听套接字上的连接的进程。当我绑定,监听并等待main()函数中的接受时,它似乎工作。但是,当我尝试创建一个新线程并绑定,监听并接受新线程时,它会失败。这是我的代码。C:pthread无法在套接字上侦听,绑定和接受

void request_handler(int clientSock) { 
    FILE *requestedFile = NULL; 
    long fileSize = 0; 
    struct stat st; 
    long bytesRead; 
    char buffer[1024]; 

    requestedFile = fopen("/PATH/book.txt", "rb"); 

    while(!feof(requestedFile)) { 
     bytesRead = fread(buffer, 1, sizeof(buffer), requestedFile); 
     send(clientSock, buffer, bytesRead, 0); 
    } 

} 

void listener() { 
    int server_sock_desc; 
    struct sockaddr_in name; 

    int client_sock_desc; 
    struct sockaddr_in client_name; 
    socklen_t addr_size; 

    pthread_t handler_thread; 

    printf("waiting"); 

    //connection setup 
    server_sock_desc = socket(PF_INET, SOCK_STREAM, 0); 


    if(server_sock_desc != -1) { 
     memset(&name, 0, sizeof(name)); 
     name.sin_family = AF_INET; 
     name.sin_port = htons(5000); 
     name.sin_addr.s_addr = htonl(INADDR_ANY); 
     int bind_result = bind(server_sock_desc, (struct sockaddr *) &name, sizeof(name)); 
     if(bind_result == 0) { 
      if(listen(server_sock_desc, BACKLOG) < 0) { 
       perror("listen failed"); 
      } 

      addr_size = sizeof(client_name); 

      //Server Loop will continue to run listening for clients connecting to the server 
      while(1) { 

       //new client attempting to connect to the server 

       client_sock_desc = accept(server_sock_desc, (struct sockaddr *) &client_name, &addr_size); 
       if(client_sock_desc == -1) { 
        if(errno == EINTR) { 
         continue; 
        } 
        else { 
         perror("accept failed"); 
         exit(1); 
        } 
       } 

       //connection starts here 

       //create a thread for the new clients request to be handled 
       if(pthread_create(&handler_thread, NULL, request_handler, client_sock_desc) != 0) { 
        perror("pthread_create failed"); 
       } 
      } 
     } 
     else { 
      perror("bind failed"); 
     } 
    } 
    else { 
     perror("socket failed"); 
    } 

} 

int main(int argc, const char * argv[]) 
{ 
    pthread_t listenerThread; 

    if(pthread_create(&listenerThread, NULL,listener, NULL) != 0) { 
     perror("Listener thread create failed"); 
    } 
} 

奇怪的是,当我试图通过一个调试器,有时听众的一部分来运行它()会执行,然后只停留无章可循。

+0

定义“它失败”。 – EJP 2013-05-05 10:06:43

回答

5

您需要给线程一个运行的机会。您的程序在创建线程后立即终止(从main返回)!

如果您希望您的初始线程终止并使其他线程继续运行,请拨打pthread_exit而不是从main返回。如果您希望该线程等待侦听线程终止,请在侦听线程上调用pthread_join

您让初始线程跑离地图的边缘。有龙。

+0

谢谢!我从来没有想到这一点。我是线程新手。几分钟后我接受 – user2158382 2013-05-04 19:09:46