- 非阻塞IO:
- 若资源
没有
准备就绪
,立即返回错误信息
;
- 若资源准备就绪,会
获取
相关资源
;
- 特点:
- 在所有的
IO模型
中,进程不会阻塞
、轮询
访问,CPU消耗
较大;
- 设置非阻塞(fcntl函数):
- fcntl
函数功能
:控制文件描述符
状态;
- fcntl函数:
#include
#include
int fcntl(int fd, int cmd, ... );
int flag = fcntl(fd, F_GETFL);
flag |= O_NONBLOCK;
fcntl(fd, F_SETFL, flag);
#include
#include
#include
#include
#include
#include
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
#include
#include
#include
#include
#include
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
#include
#include
#include
#include
#include
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
#include
#include
#include
#include
#include
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:hi
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:hello
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:
myfifo1:
myfifo2:
myfifo3:china
myfifo1:
myfifo2:
myfifo3: