非阻塞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$ 

猜你喜欢

转载自blog.csdn.net/andrewgithub/article/details/81589067
今日推荐