Re: multiple read() calls
- From: Sergei Organov <osv@xxxxxxxxx>
- Date: Thu, 24 Jan 2008 13:21:13 +0300
"subramanian100in@xxxxxxxxx, India" <subramanian100in@xxxxxxxxx> writes:
I am using Redhat Enterprise Linux kernel 2.6.9 with gcc 3.4.3
Consider the following program.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc, char** argv)
{
char arr[5] = { 0 };
ssize_t no_of_chars_read;
errno = 0;
if ((no_of_chars_read =
read(STDIN_FILENO, arr, sizeof(arr) - 1)) < 0)
{
printf("read() failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
errno = 0;
if (write(STDOUT_FILENO, arr, no_of_chars_read) !=
no_of_chars_read)
{
printf("write() failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
errno = 0;
if ((no_of_chars_read =
read(STDIN_FILENO, arr, sizeof(arr) - 1)) < 0)
{
printf("second read() failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
errno = 0;
if (write(STDOUT_FILENO, arr, no_of_chars_read) !=
no_of_chars_read)
{
printf("write() failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
When I run this program as
[subbu@localhost doubts]$ ./a.out
1234567890abcdefghijklmnopqrstuvwxyz
the following output is produced:
12345678[subbu@localhost doubts]$ 90abcdefghijklmnopqrstuvwxyz
bash: 90abcdefghijklmnopqrstuvwxyz: command not found
[subbu@localhost doubts]$
My questions:
1)The second read() call does not wait for input. How does the second
read() call get input? Shouldn't the characters remaining after the
first read() call be ignored(looks like the characters remaining after
the first read() call are available in some buffer which I am unable
to understand) ?
Sure the characters are buffered. What don't you understand about it?
2)How does "90abcdefghijklmnopqrstuvwxyz" get printed at the command
prompt?
Your program only reads first 8 bytes of entire input, and the rest are
then read by the shell after your program returns. Shell then tries to
interpret these bytes as command and prints error message as there is no
such command.
-- Sergei.
.
- References:
- multiple read() calls
- From: subramanian100in@xxxxxxxxx, India
- multiple read() calls
- Prev by Date: multiple read() calls
- Next by Date: Re: print something on console at the position I want with printf?
- Previous by thread: multiple read() calls
- Index(es):
Relevant Pages
|