Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

374
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda