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;
}