套接字接受-即使调用close(sd),“打开的文件太多”

时间:2019-12-08 21:22:51

标签: c sockets http tcp

我正在C中的HTTP服务器端工作。从请求处理到将文件加载到客户端的所有操作都可以正常工作。问题是刷新页面后我最终得到了Socket accept - “Too many open files”。接受新客户的主要代码是:

while(1)
{
    int client;
    thData * td;     
    int length = sizeof (from);

    if ( (client = accept (sd, (struct sockaddr *) &from, &length)) < 0)
    {
        perror ("[server]Eroare la accept().\n");
        continue;
    }

    td = (struct thData*)malloc(sizeof(struct thData)); 
    td->idThread = i++;
    td->cl = client;
    printf("Open: %d\n", td->cl);
    pthread_create(&th[i], NULL, &treat, td);                   
}//while    
static void *treat(void * arg)
{       
    struct thData tdL; 
    tdL= *((struct thData*)arg);

    fflush (stdout);         
    pthread_detach(pthread_self()); 

    raspunde((struct thData*)arg); /*read write etc*/

    printf("Close: %d(%d)\n", tdL.cl, close (tdL.cl));
    return(NULL);   
}

逻辑是我有100个最大线程来处理请求。问题是我认为我没有正确使用close函数,因为即使我用返回值0关闭了它们,我最终还是打开了许多套接字描述符。这可能是什么问题?是线程同步吗?

下面是一次刷新后的返回值。即使我关闭了它们,它也打开了很多描述符,甚至跳过了一些。达到1024 ulimit -n的那一刻便破了。

Open: 12
Close: 12(0)
Open: 13
Close: 13(0)
Open: 18
Close: 18(0)
Open: 13
Close: 13(0)
Open: 18
Close: 18(0)
Open: 13
Close: 13(0)
Open: 18
Close: 18(0)
Open: 13
Open: 25
Close: 13(0)
Close: 25(0)
Open: 13
Open: 25
Close: 25(0)
Close: 13(0)
Open: 27
Close: 27(0)
Open: 13
Close: 13(0)
Open: 31
Close: 31(0)
Open: 13
Close: 13(0)
Open: 31
Open: 13
Close: 31(0)
Close: 13(0)
Open: 31
Close: 31(0)
Open: 31
Close: 31(0)
Open: 38
Open: 31
Close: 38(0)
Open: 38
Close: 31(0)
Close: 38(0)
Open: 38
Close: 38(0)
Open: 57
Close: 57(0)
Open: 38
Close: 38(0)
Open: 57
Close: 57(0)
Open: 38
Close: 38(0)
Open: 57
Close: 57(0)
Open: 38
Close: 38(0)
Open: 57
Close: 57(0)
Open: 57
Close: 57(0)
Open: 63
Close: 63(0)
Open: 63
Close: 63(0)
Open: 65
Close: 65(0)
Open: 63
Close: 63(0)
Open: 65
Close: 65(0)
Open: 63
Close: 63(0)
Open: 65
Close: 65(0)
Open: 63
Close: 63(0)

0 个答案:

没有答案