what am i missing here??

Discussion in 'C' started by xabhi, Sep 2, 2010.

  1. xabhi

    xabhi New Member

    Joined:
    Sep 2, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Here's a code i wrote to find out how non-blocking read works...
    Code:
    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
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice