Equinox
Equinox

Reputation: 23

Read loop wont terminate

I can't seem to get this read loop to terminate.

#include <unistd.h>
char buffer[256];
int read_chars;
while((read_chars = read(STDIN_FILENO,buffer,sizeof(buffer))) > 0) { 
  //DO STUFF
} 

However, when I hit enter in the terminal, it just hangs for the next read and never exits.

Any thoughts on this implementation is not correct ?

Upvotes: 0

Views: 374

Answers (1)

Victor Schubert
Victor Schubert

Reputation: 323

Here read will stop reading at the end of standard input, which a newline isn’t. Try doing Ctrl-D twice in your terminal while the program is reading and it should terminate. Ctrl-D once on an empty line or twice after some characters marks the end of standard input.

Upvotes: 1

Related Questions