首页 > thread正确处理socket后抛出错误

thread正确处理socket后抛出错误

最近在学习写个简单的http server,流程是来个request就开个线程处理,然后主线程循环accept,但处理request的线程正常运行结束后总是抛出个stat error:no such file or directory。代码如下:

while(true)
{
    int client=accept(listen_sock,(sockaddr*)&remote,&len);
    if(client<0)
        die_err(std::string("accept error").c_str());

    std::thread(process_request,client).detach();
}

void process_request(int client)
{
    std::string method;
    char line[1024];
    std::string firstline;
    std::string path;
    std::string htoc("/Users/imagecmos/untitled");
    if(recv(client,line,sizeof(line),0)<0)
        die_err(std::string("recv error").c_str());
    getline(line, sizeof(line),method,path,firstline);
    htoc+=path;
    struct stat urlpath;
    if(stat(htoc.c_str(),&urlpath)<0)
        die_err(std::string("stat error").c_str());
    if(S_ISDIR(urlpath.st_mode))
    {
        _default(client);
    }
    else if(S_ISREG(urlpath.st_mode))
    {
        normalresponse(client,htoc);
    }
    close(client);
}

奇怪的是我把while(true)去掉,这个错误就没了,请问是什么原因?调了好长时间没看出问题。


题主是不是在第一次请求返回之后把文件做了修改,改名字或者删除或者移动了?所以第二次相同的请求过来就找不到文件。

给的信息有点少,不太会看


if(stat(htoc.c_str(),&urlpath)<0)
        die_err(std::string("stat error").c_str());

出问题的地方在这里。

std::string htoc("/Users/imagecmos/untitled");

上面文件(目录)是不是存在呢?

当去掉while(true)就没有出错了,那么有两个可能。
1、你的程序只处理一个连接没有问题
2、压根就没处理,程序就退出了。因为没有while(true)所以主线程退出了,新开的分离态的线程还没有执行到这一步就退出了。
建议你还是打断点看看问题出在哪里?
第二就是

if(stat(htoc.c_str(),&urlpath)<0){
        die_err(std::string("stat error").c_str());
        close(clinet);
}

如果你这一步骤与后面的相关,应该处理这个错误。


void process_request(int client)
{
    std::string method;
    char line[1024];
    std::string firstline;
    std::string path;
    std::string htoc("/Users/imagecmos/untitled");
    if(recv(client,line,sizeof(line),0)<0)
        die_err(std::string("recv error").c_str());      
    getline(line, sizeof(line),method,path,firstline);
    htoc+=path;
    struct stat urlpath;
    if(stat(htoc.c_str(),&urlpath)<0)
        die_err(std::string("stat error").c_str());    // 楼主确定是处理结束了吗?看起来
                                                       // 错误是这里抛出的
    if(S_ISDIR(urlpath.st_mode))
    {
        _default(client);
    }
    else if(S_ISREG(urlpath.st_mode))
    {
        normalresponse(client,htoc);
    }
    close(client);
}

麻烦程序发的完整一点 。。。
我刚才还说怎么没找到while(true),原来上面是个语句块,不是函数 。。。

【热门文章】
【热门文章】