hi all;

i have run this code and the first read and write work correctly. but and the second one is missed.
the output log is:

freez@JALALI:~$ ./a
salam8a
okok2freez@JALALI:~$

#include <stdio.h>

int main()
{
write(1,"salam",5);
char a[2];
char b[5];
read(0,a,2);
if(a[0]=='8')
{write(1,"ok",2);
read(0,b,5);
write(1,"ok2",3);
}
return 0;
}

Edited 3 Years Ago by ferizhandi

"8a" is two characters, but you actually typed three. Count each key you press when running this test, and the remaining character will become clear. That character is pulled by the second read() call and due to this that call will not block for further input.

This is a variation of the classic newline bug, where a newline in the stream mucks up unsuspecting code.

Edited 3 Years Ago by deceptikon

First off, let's get this code suitably indented, so that it is readable:

#include <stdio.h>

int main()
{
    write(1,"salam",5);
    char a[2];
    char b[5];
    read(0,a,2);

    if(a[0]=='8')
    {
        write(1,"ok",2);
        read(0,b,5);
        write(1,"ok2",3);
    }
    return 0;
}

I know that for newcomers, this may make it look like modernist poetry of some sort, and the benefits may not be entirely obvious. Trust me, however, when I tell you that indented code is vastly easier to read, understand, and most importantly maintain than unindented code. The specific indent style you choose is less important than applying some sort of indentation, and being consistent with it.

Now, with that out of the way, we can look at the program sensibly. Looking at the code, the only problem I really see is that you don't have the correct header (read() and write() are low-level functions declared in <unistd.h>, not <stdio.h>), and that you don't have any newlines. If you look at the output again, you'll see that the second write() call does output, but that because there is no newline, it is on the same line as the shell prompt, making it harder to notice.

Now, you'll also note that both outputs are taking place on the same line, after both of the inputs. This is because when you enter a two-character sequence and hit enter, you are actually entering three characters: the '8', the 'a', and the newline. Since you only read two characters out of the buffer, the newline is still there, which means that the newline character is read as the input on the second call to read(). If you are certain that the input will always be exactly two character, then you can fix this by changing the first read() so that it reads in three characters, and the second so that it reads six, but this really isn't a foolproof solution.

This article has been dead for over six months. Start a new discussion instead.