您好我在C中编写一个简单的Web服务器,它只处理从浏览器发送的简单get和post请求。我不熟悉C所以调试很痛苦,但是我已经把它编译好了但是我在尝试查看网页时不断地从浏览器中得到一个err_connection_reset响应。我把它缩小到没有进入用于监听打开的套接字的主循环但它不会进入它,这是我的主要功能
int main(int argc, char *argv[])
{
printf("in main");
int portno; // port number passed as parameter
portno = atoi(argv[1]); // convert port num to integer
if (portno < 24)
{
portno = portno + 2000;
}
else if ((portno > 24) && (portno < 1024))
{
portno = portno + 1000;
}
else
{
;
}
// Signal SigCatcher to eliminate zombies
// a zombie is a thread that has ended but must
// be terminated to remove it
signal(SIGCHLD, SigCatcher);
int sockfd; // socket for binding
int newsockfd; // socket for this connection
int clilen; // size of client address
int pid; // PID of created thread
// socket structures used in socket creation
struct sockaddr_in serv_addr, cli_addr;
// Create a socket for the connection
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
error("ERROR opening socket\n");
}
// bzero zeroes buffers, zero the server address buffer
bzero((char *)&serv_addr, sizeof(serv_addr));
// set up the server address
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
// bind to the socket
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding. Did you forget to kill the last server?\n");
listen(sockfd, 5); // Listen on socket
clilen = sizeof(cli_addr); // size of client address
while (1)
{ // loop forever listening on socket
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, (socklen_t *) & clilen);
if (newsockfd < 0)
error("ERROR on accept");
// Server waits on accept waiting for client request
// When request received fork a new thread to handle it
pid = fork();
if (pid < 0)
error("ERROR on fork\n");
if (pid == 0)
{ // request received
close(sockfd);
// Create thread and socket to handle
httpthread(newsockfd, cli_addr);
exit(0);
}
else
close(newsockfd);
} /* end of while */
return 0; /* we never get here */
}
答案 0 :(得分:1)
循环只执行一次,然后程序终止,因为你在父进程中调用exit(0)。当您调用exit时,整个过程将终止,包括活动线程。这包括通过调用httpthread(newsockfd,cli_addr)创建的线程。
此外,子进程正在关闭套接字。检查您是否确实要执行此操作,并且不要在父进程内终止程序。