Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

373
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!