-
what am i missing here??
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
-
See here....looks like you need to set the device to non-canonical mode.
-
Damn, my friend had the same exact problem with nb reads quite similar to this (although not from a term).
Blahhh, can't remember for the life of me what the issue was...
-
thanks.. i know about non canonical input. the thing is that if this read was reading from an open file it would have returned after reading data from it, without the need of any key press. it's the working of read on terminals and their link to the return key. i can't find the exact definition of how a read interprets the carriage return.
-
why wont anybody answer??? why???
-
Code:
#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); // you forgot something...
sleep(2);
}
}
else {
buf[n] = '\0';
printf("read %s\n", buf);
break;
}
}
exit(0);
}
what you want is to print this:
?
if yes delete the "n"
-
corrected -
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");
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