Linux C编程笔记-----两种非阻塞的方式读取文件或终端

1.打开文件时设置

Linux编程中有时我们需要读取终端,但是我们又不想我们的程序阻塞。我们需要以非阻塞的方式来打开文件/dev/tty。
dev/tty:当前设备终端文件。

案例:

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

int main()
{
        int fd,n;
        char buf[10];
        fd=open("/dev/tty",O_RDONLY|O_NONBLOCK);//用只读和非阻塞的方式打开文件dev/tty
        if(fd<0)
        {
                perror("open dev/tty");
                exit(1);
        }

	sleep(10);//假设你有十秒的事件来从键盘输入数据到终端
        n=read(fd,buf,10);
        if(n<0)
        {
        	printf("no inputs\n");
        }else
	{
		printf("get inputs: %s\n",buf);
	}

        close(fd);
        return 0;
}

2.利用fcntl

int fd=open("/dev/tty",O_RDONLY);
	int flag=fcntl(fd,F_GETFL);
	flag|=O_NONBLOCK;
	fcntl(fd,F_SETFL,flag);

测试案例:

/*************************************************************************
    > File Name: test.c
    > Author: zhou
    > Mail:none 
    > Created Time: Fri 25 Dec 2020 09:17:36 PM EST
 ************************************************************************/

#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
	int fd=open("/dev/tty",O_RDONLY);
	int flag=fcntl(fd,F_GETFL);
	flag|=O_NONBLOCK;
	fcntl(fd,F_SETFL,flag);
	while(1)
	{
		char buf[1024]={0};
		int n=read(fd,buf,1024);
		if(n>0)
		{
			printf("%s \n",buf);
		}else if(n==0)
		{
			printf("empty\n");
		}else
		{
		
			printf("test\n");
		}
		
		sleep(2);
	}
	close(fd);
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值