为什么没有触发EPOLLOUT?

时间:2018-03-28 05:05:49

标签: c epoll

以下代码使用级别触发,因为我没有在EPOLLET中指定epoll_ctl标记。根据我的理解,这段代码应该在启动时重复打印we have polled something,因为套接字是可写的,我设置了默认的级别触发模式。但是,在启动时它只是睡在epoll_wait。我很好奇我做错了什么。

static int
make_socket_non_blocking (int sfd)
{
    int flags, s;

    flags = fcntl (sfd, F_GETFL, 0);
    if (flags == -1) {
        perror ("fcntl");
        return -1;
    }

    flags |= O_NONBLOCK;
    s = fcntl (sfd, F_SETFL, flags);
    if (s == -1) {
        perror ("fcntl");
        return -1;
    }
    return 0;
}


static int
create_and_bind (char *port)
{
    struct sockaddr_in serv_addr;

    int sfd =  socket(AF_INET, SOCK_STREAM, 0);

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(atoi(port));

    int s = bind(sfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
    if (s!=0)
        printf("bind failed\n");

    return sfd;
}


int main (int argc, char *argv[])
{
    int sfd, s;
    int efd;
    struct epoll_event event;
    struct epoll_event *events;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s [port]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    sfd = create_and_bind (argv[1]);
    if (sfd == -1)
        abort();

    s = make_socket_non_blocking(sfd);
    if (s == -1)
        abort();

    s = listen(sfd, SOMAXCONN);
    if (s == -1) {
        perror("listen");
        abort();
    }

    efd = epoll_create1(0);
    if (efd == -1) {
        perror("epoll_create");
        abort();
    }

    event.data.fd = sfd;
    event.events = EPOLLIN | EPOLLOUT;
    s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);
    if (s == -1) {
        perror("epoll_ctl");
        abort();
    }
    /* Buffer where events are returned */
    events = calloc(MAXEVENTS, sizeof event);

    /* The event loop */
    while (1) {
        int n, i;

        n = epoll_wait(efd, events, MAXEVENTS, -1);

        printf ("we have polled something\n");

        // ...
    }

    free(events);
    close(sfd);

    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:0)

被动侦听套接字不应该是可写的。