【发布时间】:2014-01-26 10:00:57
【问题描述】:
我编写了简单的 TCP/IP 多线程 ANSI C 服务器(客户端是 C 语言),一切正常,除非服务器没有从客户端接收到正确的信号,它不会结束线程并关闭其套接字(例如当客户端崩溃时) )。如果这些线程累积,最终可能会成为问题。
我将线程存储在链接列表中 - 遍历它们不是问题。但是,默认情况下它们都被 recv() 阻止,并且由于死客户端不会发送任何内容,因此它们会卡在内存中。
维护在线客户列表的正确方法是什么? (或如何检测连接断开的线程)。
struct tListItem {
pthread_t thisThread;
char* name;
int c_sockfd;
int run;
tListItem* next;
tListItem* prev;};
struct tList{
tListItem* head;
int count;};
线程代码:
while(param->run)
{
bzero(&buf, sizeof(buf));
if ((readLen = recv(param->c_sockfd, buf, BUFFSIZE, 0)) == -1)
{
perror("Read error");
param->run = 0;
}
else if (readLen > 0) {
printf("%s: %s \n", param->name, buf);
parseIncoming(param->c_sockfd, param, buf);}}
这是我检测断开连接的尝试,但这会导致服务器结束时没有消息:
void* maintenance() {
tListItem *item;
char buf[4] = "PNG";
while(1)
{
usleep(2000000);
item= threadList->head;
while(item != 0)
{
if ((send(item->c_sockfd, buf, 3, NULL)) == -1)
{
perror("Write error");
item->run = 0;
}
item = item->next;
}
}
}
【问题讨论】:
-
我建议发布一些实际代码。我猜这会促进更好的反应。
标签: c multithreading sockets tcp