here's a code i wrote to find out how non-blocking read works...
Code:
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<errno.h>
int main()
{
int fd;
int n;
char buf[1024];
char ch;
fd = open("/dev/tty", O_RDWR | O_NONBLOCK);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
while ((n = read(fd, buf, 1024)) != 0) {
if (n == -1) {
if (errno == EAGAIN) {
printf("no data\n", n);
sleep(2);
}
}
else {
buf[n] = '\0';
printf("read %s\n", buf);
break;
}
}
exit(0);
}
the thing is that i cannot really determine how this read works. just typing on the terminal doesn't make the read return and it keeps on returning -1 with errno = EAGAIN.
the data from the terminal is read only on hitting enter. so why is that needed. how can i get the tty to work like a normal file with read.
thanks