首页 > 编程语言 >tcp网络编程4—并发的io多路复用实现(fcntl非阻塞)

tcp网络编程4—并发的io多路复用实现(fcntl非阻塞)

时间:2023-03-21 23:33:32浏览次数:36  
标签:fcntl index VectorFd int vfd tcp fd io conter

fcnt_vector_fd.h

#ifndef _FCNTL_VECTOR_FD_H
#define _FCNTL_VECTOR_FD_H
typedef struct{
    int *fd;
    int conter;
    int max_conter;
}VectorFd;


extern    VectorFd *create_vector_fd(void);

extern    void      destroy_vector_fd(VectorFd *vfd);

extern    int       get_fd(VectorFd *vfd, int index);

extern    void       remove_fd(VectorFd *vfd, int fd);

extern    void      add_fd(VectorFd *vfd, int fd);

#endif
fcntl_vector_fd.c
#include <stdlib.h> #include "fcntl_vector_fd.h" #include <stdio.h> #include <errno.h> #include <string.h> //void *memcpy(void *dest, const void *src, size_t n); static void expansion_vector(VectorFd *vfd) { if(vfd->conter >= vfd->max_conter){ int *fds = (int *)malloc(vfd->conter + 5*sizeof(int)); if(fds == NULL){ perror("expansion:"); exit(1); } memcpy(fds, vfd->fd, sizeof(int) * vfd->conter); free(vfd->fd); vfd->fd = fds; vfd->max_conter += 5; } return ; } static int indexof(VectorFd *vfd, int fd) { int index = 0; for(;index < vfd->conter; index++){ if(vfd->fd[index] == fd){ return index; } } return -1; } VectorFd *create_vector_fd(void) { VectorFd *vfd = (VectorFd *)malloc(sizeof(VectorFd)); if(vfd == NULL){ perror("create:"); exit(1); } vfd->fd = (int *)malloc(5*sizeof(int)); vfd->conter = 0; vfd->max_conter = 5; return vfd; } void destroy_vector_fd(VectorFd *vfd) { if(vfd == NULL){ perror("destroy:"); exit(1); } free(vfd->fd); free(vfd); } int get_fd(VectorFd *vfd, int index) { if(vfd == NULL){ perror("get:"); exit(1); } if(index < 0 || index > vfd->conter -1){ return -1; } return vfd->fd[index]; } void remove_fd(VectorFd *vfd, int fd) { if(vfd == NULL){ perror("remove:"); exit(1); } int index = indexof(vfd, fd); if(index < 0){ return ; } for(;index < vfd->conter; index++){ vfd->fd[index] = vfd->fd[index +1]; } vfd->conter--; } void add_fd(VectorFd *vfd, int fd) { if(vfd == NULL){ perror("add:"); exit(1); } expansion_vector(vfd);//扩容 vfd->fd[vfd->conter] = fd; vfd->conter++; return ; }

 

标签:fcntl,index,VectorFd,int,vfd,tcp,fd,io,conter
From: https://www.cnblogs.com/zj-studyrecoding/p/17242064.html

相关文章