我有以下代码,我使用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;
}
}
答案 0 :(得分:1)
看起来您想要一个有效的//continue;
而不是已注释的break;
。否则while(1)
永远不会离开。在循环之后,您应该return EXIT_SUCCESS;
或exit(EXIT_SUCCESS);
或类似。