- 阻塞IO:
- 若资源
没有
准备就绪
,会阻塞等待资源
; - 若资源准备就绪,会
获取
相关资源
; - 特点:
- 在所有的
IO模型
中,阻塞IO是最简单
、最常用
、效率最低
的; - 写阻塞:
- 如
无名管道
、有名管道
等进程间的通信; - 读阻塞:
- 以
管道
为例,具体读阻塞
操作为: - 当进程执行到
读操作
的时候,若缓冲区有内容,则读取内容继续向下执行,若缓冲区没有内容,进程进入休眠态
,直到缓冲区中有内容,由内核唤醒
该进程,来读取缓冲区内容,然后继续向下执行; - 三个写端:
#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);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); }close(fd1);close(fd2);close(fd3);return 0;}
myfifo1:hellomyfifo2:worldmyfifo3:himyfifo1:chinamyfifo2:beijingmyfifo3:the create wallmyfifo1:i love umyfifo2:miss umyfifo3:miss u