gpt4 book ai didi

c++ - 只有条件为 1 的程序不进入 while 循环

转载 作者:行者123 更新时间:2023-11-28 07:25:08 25 4
gpt4 key购买 nike

您好,我正在用 C 编写一个简单的 Web 服务器,它只处理从浏览器发送的简单获取和发布请求。我不太熟悉 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 */
}

最佳答案

循环恰好执行一次,然后程序终止,因为您在父进程中调用了 exit(0)。当您调用 exit 时,整个进程都会死亡,包括事件线程。这包括通过调用 httpthread(newsockfd, cli_addr) 创建的线程。

此外,子进程正在关闭套接字。检查你是否真的想这样做,并且不要在父进程中终止程序。

关于c++ - 只有条件为 1 的程序不进入 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18881509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com