【发布时间】:2015-08-24 09:10:20
【问题描述】:
我正在使用 Pthreads(Linux) 在 C 语言中开发服务器应用程序。一切正常,客户端可以连接服务器并传输数据。面临的问题是我的软件一直停留在接受状态,直到它没有收到来自客户端的新请求。
这是我的代码:
while((connfd = accept(sock_desc, (struct sockaddr *)&echoClntAddr (socklen_t*)&clntSock)))
{
puts("Connection accepted");
if( pthread_create( &thr, NULL , connection_handler , (void*) &connfd) < 0)
{
perror("could not create thread");
return 1;
}
puts("Handler assigned");
}
我可以运行多个线程,但我的主线程卡在accept 函数上。我该如何解决这个问题,以便我可以在其他线程运行时在主线程中执行其他工作?
【问题讨论】:
-
您是否将套接字设置为非阻塞?
-
不是因为
while阻塞了socket吗? -
@Alejandro 如何将套接字设置为非阻塞?
-
@Simer
fcntl(sock_desc, F_SETFL, fcntl(sock_desc, F_GETFL, 0) | O_NONBLOCK);尝试一下,让我们知道行为 -
你不能在另一个线程中进行接受调用吗?
标签: c multithreading server