1.阻塞IO
CPU占用率低,等待资源时将任务挂起,不占用CPU资源,等到拿到资源后继续向下执行
read:
#include "head.h"
int main(void)
{
int fd = 0;
char tmpbuff[4096] = {0};
mkfifo("/tmp/myfifo", 0777);
fd = open("/tmp/myfifo", O_RDONLY);
if (-1 == fd)
{
perror("fail to open");
return -1;
}
while (1)
{
memset(tmpbuff, 0, sizeof(tmpbuff));
read(fd, tmpbuff, sizeof(tmpbuff));
printf("FIFO:%s\n", tmpbuff);
memset(tmpbuff, 0, sizeof(tmpbuff));
gets(tmpbuff);
printf("STDIN:%s\n", tmpbuff);
}
close(fd);
return 0;
}
write:
#include "head.h"
int main(void)
{
int fd = 0;
char tmpbuff[4096] = {0};
mkfifo("/tmp/myfifo", 0777);
fd = open("/tmp/myfifo", O_WRONLY);
if (-1 == fd)
{
perror("fail to open");
return -1;
}
while (1)
{
memset(tmpbuff, 0, sizeof(tmpbuff));
MY_GETS(tmpbuff);
write(fd, tmpbuff, strlen(tmpbuff));
}
close(fd);
return 0;
}
2.非阻塞IO
能够让任务不阻塞,效率低,因为没有数据时,CPU一直空转
程序步骤:
主要是获得俩个任务,一个是从终端输入,另一个是从管道输入
1.创建管道:mkfifo
2.打开管道: open
3.将文件描述符的属性中加入非阻塞属性
(1).获得文件描述符的属性:fcntl + F_GETFL;
(2).在现有的属性中加入非阻塞属性: |= O_NONBLOCK;
(3).将新的属性设置到文件描述符中: fcntl + F_SETFL;
4.循环得到俩个任务的值
(1).从管道中读取并打印:read
(2).从终端获得并打印:gets
5.关闭管道:close
详细如下
#include "head.h"
int main(void)
{
int fd = 0;
char tmpbuff[4096] = {0};
int flags;
ssize_t nsize = 0;
char *pret = NULL;
mkfifo("/tmp/myfifo", 0777);
fd = open("/tmp/myfifo", O_RDONLY);
if (-1 == fd)
{
perror("fail to open");
return -1;
}
/* 获得fd文件描述符的属性 */
flags = fcntl(fd, F_GETFL);
/* 在现有属性中加入非阻塞属性 */
flags |= O_NONBLOCK;
/* 将新属性设置回fd文件描述符 */
fcntl(fd, F_SETFL, flags);
flags = fcntl(0, F_GETFL);
flags |= O_NONBLOCK;
fcntl(0, F_SETFL, flags);
while (1)
{
memset(tmpbuff, 0, sizeof(tmpbuff));
nsize = read(fd, tmpbuff, sizeof(tmpbuff));
if (nsize > 0)
{
printf("FIFO:%s\n", tmpbuff);
}
memset(tmpbuff, 0, sizeof(tmpbuff));
pret = gets(tmpbuff);