Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

375
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda