Poll () cannot detect event when socket is closed locally?

I am working on a project that will port the TCP / IP client program to the built-in ARM-Linux controller board. The client program was originally written in epoll (). However, the target platform is quite old; the only kernel available is 2.4.x, and epoll () is not supported. So I decided to rewrite the I / O loop in poll ().

But when I test the code, I found that poll () does not work as I expected: it will not return when the TCP / IP client socket is closed locally by another thread. I wrote very simple codes to do some tests:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <pthread.h>
#include <poll.h>

struct pollfd   fdList[1];

void *thread_runner(void *arg)
{
    sleep(10);
    close(fdList[0].fd);
    printf("socket closed\n");
    pthread_exit(NULL);
}

int main(void)
{
    struct  sockaddr_in hostAddr;
    int sockFD;
    char buf[32];
    pthread_t handle;

    sockFD = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(sockFD,F_SETFL,O_NONBLOCK|fcntl(sockFD,F_GETFL,0));

    inet_aton("127.0.0.1",&(hostAddr.sin_addr));
    hostAddr.sin_family = AF_INET;
    hostAddr.sin_port  = htons(12345);
    connect(sockFD,(struct sockaddr *)&hostAddr,sizeof(struct sockaddr));

    fdList[0].fd = sockFD;
    fdList[0].events = POLLOUT;

    pthread_create(&handle,NULL,thread_runner,NULL);

    while(1) {
        if(poll(fdList,1,-1) < 1) {
            continue;
        }
        if(fdList[0].revents & POLLNVAL ) {
            printf("POLLNVAL\n");
            exit(-1);
        }
        if(fdList[0].revents & POLLOUT) {
            printf("connected\n");
            fdList[0].events = POLLIN;
        }
        if(fdList[0].revents & POLLHUP ) {
            printf("closed by peer\n");
            close(fdList[0].fd);
            exit(-1);
        }
        if(fdList[0].revents & POLLIN) {
            if( read(fdList[0].fd, buf, sizeof(buf)) < 0) {
                printf("closed by peer\n");
                close(fdList[0].fd);
                exit(-1);
            }
        }
    }
    return 0;
}

TCP, , poll() () . : "POLLNVAL" , .

poll()? , select() poll()?

+3
1

, . , shutdown() close().

. http://www.faqs.org/faqs/unix-faq/socket/ 2.6

EDIT: , , , poll() select() , fd. close() fd, , , .

+7

Source: https://habr.com/ru/post/1793004/


All Articles