系列之非阻塞IO"/>
IO学习系列之非阻塞IO
- 非阻塞IO:
- 若资源
没有
准备就绪
,立即返回错误信息
; - 若资源准备就绪,会
获取
相关资源
; - 特点:
- 在所有的
IO模型
中,进程不会阻塞
、轮询
访问,CPU消耗
较大; - 设置非阻塞(fcntl函数):
- fcntl
函数功能
:控制文件描述符
状态; - fcntl函数:
#include <unistd.h>#include <fcntl.h>int fcntl(int fd, int cmd, ... /* arg */ );/*参数:fd 文件描述符cmd 要控制的方式F_GETFL 获取文件描述符的状态 arg被忽略F_SETFL 设置文件描述符的状态 arg为int类型文件描述符的状态 O_NONBLOCK 表示非阻塞... 可变参 有没有 以及什么类型 都取决于 cmd返回值:cmd是 F_GETFL 成功 返回文件状态标志位 失败返回-1 重置错误码 cmd是 F_SETFL 成功 返回 0 失败返回-1 重置错误码*/
int flag = fcntl(fd, F_GETFL); //先获取原来的状态信息flag |= O_NONBLOCK; //添加非阻塞的标志位fcntl(fd, F_SETFL, flag); //再设置回去
- 三个写端:
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <stdbool.h>int main(int argc, char const *argv[]){int fd = open("myfifo1",O_WRONLY);char buf[128] = {0};while(true){memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),stdin);buf[strlen(buf)-1] = '\0';write(fd,buf,sizeof(buf));}return 0;}
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <stdbool.h>int main(int argc, char const *argv[]){int fd = open("myfifo2",O_WRONLY);char buf[128] = {0};while(true){memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),stdin);buf[strlen(buf)-1] = '\0';write(fd,buf,sizeof(buf));}return 0;}
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <stdbool.h>int main(int argc, char const *argv[]){int fd = open("myfifo3",O_WRONLY);char buf[128] = {0};while(true){memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),stdin);buf[strlen(buf)-1] = '\0';write(fd,buf,sizeof(buf));}return 0;}
- 一个读端:
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <stdbool.h>int main(int argc, char const *argv[]){int fd1 = open("myfifo1",O_RDONLY);int fd2 = open("myfifo2",O_RDONLY);int fd3 = open("myfifo3",O_RDONLY);//设置为非阻塞int flag = 0;flag = fcntl(fd1,F_GETFL);flag |= O_NONBLOCK;fcntl(fd1,F_SETFL,flag);flag = fcntl(fd2,F_GETFL);flag |= O_NONBLOCK;fcntl(fd2,F_SETFL,flag);flag = fcntl(fd3,F_GETFL);flag |= O_NONBLOCK;fcntl(fd3,F_SETFL,flag);char buf[128] = {0};while(true){memset(buf,0,sizeof(buf));read(fd1,buf,sizeof(buf));printf("myfifo1:%s\n",buf);memset(buf,0,sizeof(buf));read(fd2,buf,sizeof(buf));printf("myfifo2:%s\n",buf);memset(buf,0,sizeof(buf));read(fd3,buf,sizeof(buf));printf("myfifo3:%s\n",buf); sleep(2); //防止刷屏 }close(fd1);close(fd2);close(fd3);return 0;}
- 运行结果:
myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:himyfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:hellomyfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:myfifo1:myfifo2:myfifo3:chinamyfifo1:myfifo2:myfifo3:
- 仅供参考
更多推荐
IO学习系列之非阻塞IO
发布评论