Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

epoll-et下,响应文件内容,写缓冲区满该怎么办呢?

while ((len = read(fd, buf, sizeof(buf))) > 0) {
    int ret = write(connect_fd, buf, len);
    if(ret == -1 && errno == EAGAIN) {
        printf("缓冲区满了...
");
    }
}

在边沿模式下,我设置了connect_fd通信用套接字为非阻塞,但是在循环写数据时会发生缓冲区满的情况,我试图使用epoll_wait等待该套接字可写事件发生,但因为在套接字可读事件产生时已经做出回复,所以在这里会阻塞在epoll_wait上。

while(1) {
    printf("epoll_wait...
");
    int n = epoll_wait(epfd, events, 1024, -1);
    printf("阻塞了?
");
    int flag = 0;
    for(int i = 0; i < n; ++i) {
        if(events[i].data.fd == connect_fd && events[i].events & EPOLLOUT) {
            len = read(fd, buf, sizeof(buf));
            if(len == 0) {
                flag = 1;
            }
            write(connect_fd, buf, len);
            break;
        }
    }
    if(flag == 1) {
        break;
    }
}

请问这种情况我应该如何处理?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

应该可以用水平触发加回调函数解决这个问题。对于connect_fd而言,设置为水平触发,然后定义一个写回调函数。只要可以写,缓冲区没有满,就会触发写回调。在这个回调函数里面,读fd的内容到buf,然后向connect_fd写。为了简化问题,我们假设每次都可以把buf的内容写完。所以每次写完后,就结束回调。基本思路就这样了,还有一些出错处理等等,就不赘述了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...