In this simple code, I noticed that you are not reading stdin from the second read call, why is this happening? Since these functions are not buffered.
#include <stdio.h>
#include <unistd.h>
int main(void) {
char a, b;
write(1, "first: ", 8);
read(0, &a, 1);
write(1, "second: ", 10);
read(0, &b, 1);
putchar(a);
putchar(b);
return 0;
}
If you start your program and type (for example)
a [enter]
then two characters are pending on stdin: 'a' and '\n' (newline)
so the first call to read()
blocks, waits for input and - after you enter the character - reads in the a
.
The second call to read()
does not block, but immediately reads the second pending character (the newline \n
).
To fix this, you have to read in the newline into some dummy buffer, perhaps like this:
char a, b, dummy;
write(1, "first: ", 8);
read(0, &a, 1);
read(0, &dummy, 1);
write(1, "second: ", 10);
read(0, &b, 1);
read(0, &dummy, 1);
putchar(a);
putchar(b);
Then it should work as expected.