我在其中使用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);或类似名称。

10-08 10:53