I am trying to learn read() system call using the following code that reads from the stdin and outputs what was read to the stdout :
# include <unistd.h>
# include <stdio.h>
int main() {
int b=10;
char buff [b];
int n= read(0,buff,b);
write(1,buff,n);
printf("%d \n",n);
}
As it is clear the max. bytes to be read is 10. So I have tried the following scenarios :
-
I have entered just two characters, what I got was :
AA
AA
3
I have entered two As and then the write() has printed them to me in the second line. In the third line I am printing the returned value by read() ( see the code ) and according to my understanding, the read() should returns the number of bytes that was read. So I was expected it to be 2 since I have input only two As, why I got here 3 instead ??
-
In this scenario, I have input 11 As ( exceeding the max. bytes to read , which are 10 bytes) :
AAAAAAAAAAA
AAAAAAAAAA10
adam@adam-VirtualBox:~/La4$ AA: command not found
As you can see I wrote the 11 As in the first line , however, what was wrote by the write() is AAAAAAAAAA10only 10 As were wrote ( since I the number of bytes to write passed to the write() was 10), but what is 10in the end ? Also, A: command not found occurred because I have passed 10 bytes only to be read to the read() system call and it has rejected the 11th A , is that correct ?
>Solution :
I have entered just two characters… So I was expected it to be 2 since I have input only two As, why I got here 3 instead ??
You do not enter characters. You press keys on a keyboard. The hardware and software translate key presses into characters. You pressed A, A, and Return or Enter. The computer translated those into an A character, an A character, and a newline character.
In this scenario, I have input 11 As…
Pressing A eleven times and then pressing Return or Enter resulted in eleven A characters and a newline character in the terminal’s input buffer. Your program read ten of them, because that is all you told the read call to read. Then your program ended, which left an A character and a newline character in the input buffer. After your program ended, the command-line shell resumed running. It tried to read a command, and it was given the two characters in the input buffer, the A and the newline. It attempted to interpret that as a command, but there is no A command to run, so the command-line shell gave you an error message.