非阻塞IO -- 阻塞IO
补充:有限状态机编程
- 非阻塞IO
- 简单流程:自然流程是结构化的
- 复杂流程:自然流程不是结构化的(网络协议)
- IO多路转接(文件描述符的监视)
- select(): 以事件为单位组织文件描述符,移植性好,设计缺陷
- poll():以文件描述为单位组织事件
- epoll():linux方言,不能移植,效率高
- int epfd epoll_create(int size)
- epoll_ctl(int epfd, int op, int fd, struct epoll_event *event):对epfd实例中的fd文件描述符进行op操作(add,mod,del)
- epoll_wait(int epfd , struct epoll_event *events, int maxevents, int timeout)
- close(eppfd);
- 其他读写函数
- readv(int fd, const struct iovec *iov, int iovnt); 用于读写地址不是连续的数据块
- writev(int fd, const struct iovec *iov, int iovnt);
-
struct iovec{ void *iov_base; //数组首地址 size_t iov_len; //数组长度 }
- 存储映射IO
- void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); 将一块内存空间数据映射到进程空间. 可实现非常好用的共享内存
- int*munmap(void *addr, size_t length);
-
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/mman.h> #include<string.h> #define MEMSIZE 1024 int main() { char *ptr; pid_t pid; ptr = mmap(NULL, MEMSIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if(ptr == MAP_FAILED) { perror("mmap()"); exit(1); } pid = fork(); if(pid < 0) { perror("fork()"); munmap(ptr, MEMSIZE); exit(1); } if(pid == 0) //child write { strcpy(ptr, "Hello!"); munmap(ptr, MEMSIZE); exit(0); } else { wait(NULL); puts(ptr); munmap(ptr, MEMSIZE); exit(0); } }
- 文件锁
- fcntl();
- lockf();
- flock();