2013-10-20 43 views
0

我正在做C中的套接字编程。本质上,我需要一个服务器在单独的线程中运行无限制的侦听循环,并且只要它接受一个新的连接,就必须创建一个新的客户端线程处理客户的请求。Listening线程不打印语句

下面我有主要函数声明端口号,并调用函数createListenThread。此函数创建一个新线程并调用函数listenLoop

int main(int argc, char *argv[]) 
{ 
    int client_port = 6000; 
    createListenThread(client_port); 
} 

void createListenThread(int listen_port) 
{ 
    pthread_t listen_tid; 

    printf("In createListenThread\n"); 
    // listenLoop(&listen_port); 

    if(pthread_create(&listen_tid, NULL, listenLoop, &listen_port) != 0) 
     socketError("Could not create thread\n");  

} 

void *listenLoop(void *arg) 
{ 
    pthread_detach(pthread_self()); 

     int listen_socket, listen_port, *client_socket, struct_size; 
    struct sockaddr_in client_addr; 
    pthread_t client_tid; 

    listen_port = *((int *)arg);   
    listen_socket = createSocket(listen_port); 
    struct_size = sizeof(struct sockaddr_in); 

    while(1) 
    { 
     printf("In ListenLoop\n"); 
      client_socket = malloc(sizeof(int)); 
      *client_socket = -1; 
      *client_socket = accept(listen_socket, (struct sockaddr *)&client_addr, &struct_size); 

      printf("Received connection request from (%s , %d)\n", 
      inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); 

      pthread_create(&client_tid, NULL, starterFunction, client_socket); 
    } 

    close(listen_socket); 
} 

我的问题是,每当我运行服务器,只有“在ListenThread”“在ListenLoop”从不打印。我甚至试过fprintf(标准输出,“在ListenLoop”)和fflush(标准输出),但声明仍然没有打印。当我注释掉:

if(pthread_create(&listen_tid, NULL, listenLoop, &listen_port) != 0) 
     socketError("Could not create thread\n"); 

,并简单地调用ListenLoop如下:

listenLoop(&listen_port); 

两个打印语句出现。在创建线程和调用ListenLoop函数的方式中是否有明显的错误? ListenLoop函数是否被执行过?

编辑:我跑在gdb的程序,其打印执行以下操作:

In createListenThread 
[New Thread 0xb7e30b70 (LWP 10024)] 
[Thread 0xb7e30b70 (LWP 10024) exited] 
[Inferior 1 (process 10021) exited normally] 

为什么线程退出??

+0

主线程立即退出。你需要一些投入运营添加到它,像“按Enter键退出” + scanf函数。 –

回答

2

问题在于您的主函数在调用createListenThread后立即返回。您应该等待您的线程函数在您的createListenThread内完成使用pthread_join,否则程序可能会在线程函数完成之前终止。在线索上调用pthread_join将等待线程函数返回,因此肯定有机会在main()返回之前运行。

+0

如果我添加在pthread_join(listen_tid,NULL),它解决了被印刷在原始问题即线程不再存在并且statment“以ListenLoop”。但是,有一个问题会破坏创建单独监听线程的全部目的。这会阻塞主线程,即主线程不能继续执行其他工作。有没有解决这个问题的工作? – NewToAndroid

+0

当主进程在主完成后终止时,所有线程也被终止。我相当肯定这没有解决方法,但如果有的话,我相信有人会纠正我。 – mathematician1975

+0

@NewToAndroid阅读这个类似问题的一些答案 - 它是我的帮助http://stackoverflow.com/questions/11875956/main-thread-exit-does-other-exit-too – mathematician1975

0

我希望你声明所有的功能,上述主要...但你真的应该打电话给你的listenLoop在主线程。否则,你创建一个线程来运行循环,主线程被动地等待它。而且你不会被参数传递,线程等待等困扰。

listenLoop然后可以是一个真正的无效,不再是一个void *,因为你不返回任何东西。

如果你把一个进程,它将使意义,因为它是建立由init进程采取的守护进程immediateley正确的方法,但对于它的线程是根本没用。