gpt4 book ai didi

c++ - Fork() 调用 - 程序从未终止

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

我有以下代码,我在其中使用了 fork。问题是,当我使用内部的 fork 调用调用该函数时,我的主程序没有终止(尽管它工作正常并且可以执行我想要的操作)并且我无法找出原因。我提前感谢任何帮助。

while(1)
{
ClientSocket = accept(m_ServerSocket, 0, 0); //Accept the client;

if(ClientSocket == SOCKET_ERROR)
cout << "Problem while connecting with client" << endl;

pid = fork();

if (pid < 0)
{
perror("ERROR on fork");
exit(1);
}

else if(pid==0)
{
close(m_ServerSocket);
int nBytes;

char inMessage[100]; // The actual buffer

nBytes = recv(ClientSocket, inMessage, sizeof(inMessage), 0); // Receive at MAX sizeof(inMessage) bytes into inMessage from the client using clientSocket
if (nBytes == SOCKET_ERROR)
cout << "Server: Ah ****... I didn't get it...\n";

cout << "Received: " << inMessage << endl;
exit(0);
}

else
{
close(ClientSocket);//In Windows use closesocket() instead.
//continue;
}
}

最佳答案

看起来您想要的不是注释掉的//continue;,而是一个活跃的break;。否则 while(1) 永远不会离开。在循环之后,您应该return EXIT_SUCCESS;exit(EXIT_SUCCESS); 或类似的。

关于c++ - Fork() 调用 - 程序从未终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20347103/

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