一、代码
#include <fcntl.h>
fcntl()
O_NONBLOCK
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
//fcntl()
//O_NONBLOCK
int main(int argc, char*argv[])
{
//
int flag = fcntl(STDIN_FILENO, F_GETFL);
flag |= O_NONBLOCK;
//
if (fcntl(STDIN_FILENO, F_SETFL, flag) < 0)
{
perror("fcntl error");
exit(1);
}
char buf[20];
int n;
tryagain:
n = read(STDIN_FILENO, buf, 10);
if (n < 0)
{
if (errno == EAGAIN)
{
sleep(1);
write(STDOUT_FILENO, "try again\n", strlen("try again\n"));
goto tryagain;
}
perror("read /dev/tty error");
exit(1);
}
write(STDOUT_FILENO, buf, n);
return 0;
}
二、输出结果