最近在学习写个简单的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)去掉,这个错误就没了,请问是什么原因?调了好长时间没看出问题。
Did the questioner modify the file, change its name, delete or move it after the first request was returned? So the second time the same request comes, the file cannot be found.
The information given is a bit lacking and I’m not very good at reading it
Please post the program more completely. . .
I just said why I couldn't find
while(true)
. It turns out that it is a statement block, not a function. . .Here is the problem.
Does the above file (directory) exist?
When you remove
while(true)
and there is no error, then there are two possibilities.1. Your program only handles one connection, no problem
2. It doesn’t handle it at all, and the program exits. Because there is no
while(true)
, the main thread exits, and the newly opened separate thread exits before executing this step.I suggest you stop and see where the problem lies?
The second is
If your step is related to the later one, you should handle this error.