非阻塞IO-读数据

阻塞型看:阻塞IO读数据
使用set_fl(STDIN_FILENO, O_NONBLOCK);将输入输出设置为非阻塞时,read()函数等不到数据输入的时候就会直接返回出错信息,而不是继续等到用户输入。

#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


int main(void)
{
    char buffer[4096] = {'\0'};  //因为使用电脑的缓存区大小是4096
    ssize_t size = 0;


    //设置非阻塞形式IO
    set_fl(STDIN_FILENO, O_NONBLOCK);

    sleep(5);


    size = read(STDIN_FILENO, buffer, sizeof(buffer));
    if(size < 0)
    {
        perror("read error!");
        exit(1);
    }
    else if(size == 0)
    {
        printf("read finished!\n");
    }
    else
    {
        if(write(STDOUT_FILENO, buffer, size) != size)
        {
            perror("write error!");
            exit(1);
        }
    }

    return 0;

}




void set_fl(int fd, int flags) /* flags are file status flags to turn on */
{
    int        val;

    if ( (val = fcntl(fd, F_GETFL, 0)) < 0)
        {
            printf("fcntl F_GETFL error");
            exit(1);
        }

    val |= flags;        /* turn on flags */
 //重新设置文件状态标志(val为新文件的文件状态标志)
    if (fcntl(fd, F_SETFL, val) < 0)
        {
            printf("fcntl F_SETFL error");
            exit(1);
        }
}

void clr_fl(int fd, int flags)
{
    int val;

    if ((val = fcntl(fd, F_GETFL, 0)) == -1)
    {
        perror("fcntl error!");
        exit(1);
    }
    val &= ~flags; /* turn flags off */

    if (fcntl(fd, F_SETFL, val) == -1)
    {
        perror("fcntl error!");
        exit(1);
    }
    return;
}


测试;

andrew@andrew-Thurley:~/work/iotec$ bin/noblock
read error!: Resource temporarily unavailable
andrew@andrew-Thurley:~/work/iotec$ 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Achou.Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值