Linux网络编程之poll

简介:

poll多路复用非阻塞模型

the poll is like select,it uses struct pollfd to replace the read_set,write_set,error_set of select,and it has no limitation of the fd number like select.
poll与select很类似,但是用struct pollfd代替了select的read_set,write_set,error_set,而且没有fd数量的限制


struct pollfd
{
int fd; /* File descriptor to poll. */
short int events; /* Types of events poller cares about. */
short int revents; /* Types of events that actually occurred. */
};
poll(<#(struct pollfd*)__fds#>, <#(nfds_t)__nfds#>, <#(int)__timeout#>);


//poll-nonblocking
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <errno.h>
#include <assert.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <string.h>

#define MAX_READ_SIZE 20*1024*1024
#define MAX_WRITE_SIZE 20*1024*1024
#define MAX_CHUNCK_SIZE 2*1024*1024
#define KEEP_ALIVE 0
/*
 * a simple server using poll 
 *
 * feilengcui008@gmail.com 
 *
 */

void run();

int main(int argc, char *argv[])
{
    run();
    return 0;
}

//struct for socket reading and writing
struct poll_fd_state {
    char read_buf[MAX_READ_SIZE];
    char write_buf[MAX_WRITE_SIZE];
    int writing;
    ssize_t readlen;
    ssize_t written_upto;
    ssize_t write_pos;
};

//error handle
void error_exit()
{
    perror("errors happen");
    exit(EXIT_FAILURE);
}

//create listening socket
int create_server_socket()
{
    int fd;
    int reuse = 1;
    if ((fd= socket(AF_INET, SOCK_STREAM, 0))<0){
        perror("error create socket");
        return fd;
    }
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))<0){
        perror("error setsockopt");
    }
    return fd;
}

//alloc poll_fd_state struct
struct poll_fd_state *alloc_poll_fd_state()
{
    //init fds_state
    struct poll_fd_state *p = (struct poll_fd_state *) malloc(sizeof(struct poll_fd_state));
    if(!p){
        return NULL;
    }
    p->readlen = p->written_upto = p->write_pos = p->writing = 0;
    // do not do the following,it will break the code
    //memset(p->read_buf, 0, sizeof(p->read_buf));
    //memset(p->write_buf, 0, sizeof(p->write_buf));
    //bzero(p->read_buf, sizeof(p->read_buf));
    //bzero(p->write_buf, sizeof(p->write_buf));

};

//free poll_fd_state struct
void free_poll_fd_state(struct poll_fd_state *p)
{
    if(p!=NULL){
        free(p);
    }
}

//set socket non-blocking
void made_nonblock(int fd)
{
    if (fcntl(fd, F_SETFL, O_NONBLOCK)<0)
        error_exit();
}

//handle read event
int do_read(struct pollfd *pfd, struct poll_fd_state *state)
{
    ssize_t result=10;
    char buf[MAX_CHUNCK_SIZE];
    while(1){
        result = recv(pfd->fd, buf, sizeof(buf), 0);
        //printf("readlen:%d\n",(int)result);
        //fflush(stdout);
        if (result<=0)
            break;
        for (int i = 0; i < result; ++i) {
            if (state->readlen < sizeof(state->read_buf)){
                state->read_buf[state->readlen++] = buf[i];
            }
            //read until '\n'
        /*
         * todo: handle the readbuffer for http
         *
         */
            /*if (buf[i]=='\n'){
                state->writing = 1;
                state->written_upto = state->readlen;
                pfd->events = POLLOUT;//register write event
                break;
            }*/
        }

    }
    //change state to write
    state->writing = 1;
    state->written_upto = state->readlen;
    pfd->events = POLLOUT;

    if (result==0)
        return 1;
    if (result<0){
        if (errno== EAGAIN)
            return 0;
        else
            return -1;
    }
    return 0;
}

//handle write event
int do_write(struct pollfd *pfd, struct poll_fd_state *state)
{
    ssize_t result;
    while(state->write_pos<state->written_upto){
        result = send(pfd->fd, state->read_buf+state->write_pos, MAX_CHUNCK_SIZE, 0);
        if (result<=0)
            break;
        state->write_pos+=result;
    }

    if (state->write_pos==state->written_upto)
        state->write_pos = state->written_upto = state->readlen = 0;
    state->writing = 0;

    if (result==0)
        return 1;
    if (result<0){
        if (errno== EAGAIN)
            return 0;
        else
            return -1;
    }
    return 0;
}

//poll loop
void do_poll(int serverfd)
{
    int MAX_SOCKET = 1024;
    struct pollfd fds[MAX_SOCKET];
    struct poll_fd_state *fds_state[MAX_SOCKET];

    //init pollfds
    for (int i = 0; i < MAX_SOCKET; ++i) {
        fds[i].fd = -1;
    }

    //add serverfd to pollfds
    fds[0].fd = serverfd;
    fds[0].events = POLLIN;
    fds[0].revents = 0;
    int max = 0;
    int ready = -1;
    //poll begin
    while(1){
        ready = poll(fds, max+1, 0);
        if (ready<0){
            perror("poll error");
            return;
        }
        //listening socket ready to be read?
        if(fds[0].revents & POLLIN==POLLIN){
            struct sockaddr_in client;
            socklen_t slen = sizeof(client);
            memset(&client, 0, sizeof(client));
            int clientfd = accept(fds[0].fd, (struct sockaddr *)&client, &slen);
            made_nonblock(clientfd);
            if (clientfd<0){
                error_exit();
            }
            //find a slot in fds
            int i;
            for (i = 0; i < MAX_SOCKET; ++i) {
                if (fds[i].fd==-1){
                    fds[i].fd=clientfd;
                    fds[i].events= POLLIN;
                    struct poll_fd_state *p = alloc_poll_fd_state();
                    if(p==NULL){
                    error_exit();
                            }
                    fds_state[i] = p;
                    break;
                }
            }
            //reset max
            if(i>max){
                max = i;
            }
        }
        //handle client socks
        for (int j = 1; j < max+1; ++j) {
            int flag=0;
            if (fds[j].fd==-1) continue;
            if ((fds[j].revents & POLLIN)== POLLIN) flag= do_read(&fds[j], fds_state[j]);
            if (flag==0&&((fds[j].revents& POLLOUT)== POLLOUT)){
            flag = do_write(&fds[j], fds_state[j]);
        //if not set keepalive,we close the sock nomatter what flag is
        if (!KEEP_ALIVE){
            close(fds[j].fd);
            fds[j].fd = -1;
            free_poll_fd_state(fds_state[j]);
            fds_state[j] = NULL;
        }
        }
        //handle read-write error
            if (flag){
                close(fds[j].fd);
                fds[j].fd = -1;
                free_poll_fd_state(fds_state[j]);
                fds_state[j] = NULL;
            }
        }
    } 

}

void run()
{

    struct sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port = htons(8000);

    int serverfd = create_server_socket();
    if(bind(serverfd, (struct sockaddr *)&sin, sizeof(sin))<0){
        error_exit();
    }

    if (listen(serverfd, 20)<0){
        error_exit();
    }

    made_nonblock(serverfd);
    do_poll(serverfd);
}   
相关文章
|
1月前
|
监控 安全 Linux
在 Linux 系统中,网络管理是重要任务。本文介绍了常用的网络命令及其适用场景
在 Linux 系统中,网络管理是重要任务。本文介绍了常用的网络命令及其适用场景,包括 ping(测试连通性)、traceroute(跟踪路由路径)、netstat(显示网络连接信息)、nmap(网络扫描)、ifconfig 和 ip(网络接口配置)。掌握这些命令有助于高效诊断和解决网络问题,保障网络稳定运行。
80 2
|
3月前
|
安全 Linux 网络安全
Web安全-Linux网络协议
Web安全-Linux网络协议
80 4
|
1月前
|
域名解析 网络协议 安全
|
2月前
|
运维 监控 网络协议
|
1月前
|
存储 Ubuntu Linux
2024全网最全面及最新且最为详细的网络安全技巧 (三) 之 linux提权各类技巧 上集
在本节实验中,我们学习了 Linux 系统登录认证的过程,文件的意义,并通过做实验的方式对 Linux 系统 passwd 文件提权方法有了深入的理解。祝你在接下来的技巧课程中学习愉快,学有所获~和文件是 Linux 系统登录认证的关键文件,如果系统运维人员对shadow或shadow文件的内容或权限配置有误,则可以被利用来进行系统提权。上一章中,我们已经学习了文件的提权方法, 在本章节中,我们将学习如何利用来完成系统提权。在本节实验中,我们学习了。
|
2月前
|
Ubuntu Linux 虚拟化
Linux虚拟机网络配置
【10月更文挑战第25天】在 Linux 虚拟机中,网络配置是实现虚拟机与外部网络通信的关键步骤。本文介绍了四种常见的网络配置方式:桥接模式、NAT 模式、仅主机模式和自定义网络模式,每种模式都详细说明了其原理和配置步骤。通过这些配置,用户可以根据实际需求选择合适的网络模式,确保虚拟机能够顺利地进行网络通信。
115 1
|
2月前
|
网络协议 安全 Ubuntu
Linux中网络连接问题
【10月更文挑战第3天】
40 1
|
2月前
|
Linux C++
Linux C/C++之IO多路复用(poll,epoll)
这篇文章详细介绍了Linux下C/C++编程中IO多路复用的两种机制:poll和epoll,包括它们的比较、编程模型、函数原型以及如何使用这些机制实现服务器端和客户端之间的多个连接。
38 0
Linux C/C++之IO多路复用(poll,epoll)
|
2月前
|
监控 Linux 测试技术
Linux系统命令与网络,磁盘和日志监控总结
Linux系统命令与网络,磁盘和日志监控总结
70 0
|
2月前
|
监控 Linux 测试技术
Linux系统命令与网络,磁盘和日志监控三
Linux系统命令与网络,磁盘和日志监控三
49 0