下面的代码是一个TCP服务器。

bool Run()
{
    bool result = false;
    m_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (INVALIDE_SOCKET == m_Socket)
    {
        printf("Invalide socket...");
        return result;
    }

    sockaddr_in servAddr;
    unsigned int sockAddrSize = sizeof(sockaddr_in);
    bzero(&servAddr, sockAddrSize);
    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servAddr.sin_port = htons(m_Port);

    if (0 != bind(m_Socket, (sockaddr *)&servAddr, sockAddrSize))
    {
        printf("Can not bind socket addres to socket file...\n");
        return result;
    }

    if (0 != listen(m_Socket, MAX_CONNECTION))
    {
        printf("Can not listen socket...\n");
        return result;
    }


    printf("Server is stared. Please enter any key to continue...\n");
    getchar();
    system("clear");

    m_Listener.Start();
    m_DataReader.Start();

    sockaddr_in temp;
    while (true)
    {
        bzero(&temp, sockAddrSize);
        int tempSocket = accept(m_Socket, (sockaddr *)&temp, &sockAddrSize);

        if (-1 == tempSocket)
        {
            printf("accept is fialed...\n");
        }
        else
        {
            printf("A connection is established!\n");
        }

        //This is my intention:blocking after the client is connected and before the client to be send any data.
        //When the client sends data, the program will print '---------------'.
        pollfd tempTest;
        tempTest.events = POLLRDNORM;
        tempTest.revents = 0;
        tempTest.fd = tempSocket;

        int pollRes = poll(&tempTest, 1, -1);
        if (pollRes == 1 && POLLRDNORM == tempTest.revents)
        {
          printf("-------------------\n");
        }

    }
    return  result;
}

事实上,当客户机连接到服务器并且不发送任何数据时,以下代码不符合我的意图,因为它没有被阻止并且也没有被打印“-----”:
    //This is my intention:blocking after the client is connected and before the client to be send any data.
    //When the client sends data, the program will print '---------------'.
    pollfd tempTest;
    tempTest.events = POLLRDNORM;
    tempTest.revents = 0;
    tempTest.fd = tempSocket;

    int pollRes = poll(&tempTest, 1, -1);
    if (pollRes == 1 && POLLRDNORM == tempTest.revents)
    {
      printf("-------------------\n");
    }

最佳答案

你读过手册吗?
您应该测试poll的结果,因此代码:

fflush(NULL);
int res = poll(&test, 1, -1);
if (res < 0) {
  perror("poll");
  exit(EXIT_FAILURE); /// or some other error handling
};
printf("poll gave %d\n", res);

顺便说一句,我会在轮询之前调用poll(2),并且至少出于调试目的打印poll的结果。
你当然想在成功后处理follfd.revents;你应该特别注意它是poll还是POLLNVAL
你也应该同样地测试fflush(3)(在POLLERR之前,你应该socket(2)bind(2)它,看connect(2)可能socket(7)tcp(7);我想这就是poll失败或说pollPOLLNVAL的原因!)
阅读unix(7)

关于linux - 我对以下在POSIX中使用民意调查功能的代码感到困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25999964/

10-13 05:49