简体   繁体   中英

How does the read() function work? (What happens to the unread data in the buffer?)

I was trying to read input from the terminal using read() in a while loop as a condition, but the code doesn't get executed until the loop ends.

Here is my code:

#include<unistd.h>
int main(void)
{
    char ch;
    while(read(STDIN_FILENO,&ch,1) == 1 && ch != 'q')
    {
        printf("success");
    }
    return 0;
}

it gives me the output :

t
fgr
vr

q
successsuccesssuccesssuccesssuccesssuccesssuccesssuccesssuccesssuccess

Even when I try to normally read data, the unread data in the buffer ends up like this.

code:

#include<unistd.h>
int main(void)
{
    char ch;
    read(STDIN_FILENO,&ch,1);
    return 0;
}

output in terminal

user1@lap:~/Desktop$ ./program2e3
ted
pradeep@LLP:~/Desktop$ ed

Why does the unread data become the next command?

Because the data is still in the IO buffer in kernel rather than the STDIO buffer in your process, the unread data will be read by the next process that tries to read it (that is, the shell process). This is because the open handle was passed from the shell process to your process. Had you opened the tty device yourself that wouldn't have happened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM