Unistd.h read () reads more data and then writes

I am reading / writing data from a named pipe. On the writing side it says that it writes a constant of 110 bytes. The read side says for most of the time that it reads 110 bytes, which is correct, but other times it says that it reads 220 bytes or 330 bytes. What's right is that when I print it out, it prints the same message two or three times in a row in the same read (). In the below code to read, am I doing something wrong with memset to clear the char? I can't think of any other way to read it and then write if there is nothing left in the buffer.

int fd1, numread;
char bufpipe[5000];

    while(1)
    {
        fd1 = open("/tmp/testPipe", O_RDONLY);
        numread = read(fd1,bufpipe, 5000);//->this should always be 110
        if(numread > 1)
        {
            printf("READ: %i", numread); 
            bufpipe[numread+1] = '\0';
            memset(bufpipe,'\0',5001);
            close(fd1);
        }
    }

      

0


a source to share


3 answers


It:

memset(bufpipe,'\0',5001);

      

is overwritten with one byte because you only have 5000 bytes.



But the main "problem" is that read(..., 5000)

it will always read as much as it can up to 5000 bytes - you seem to be assuming that it will only read as much as was written at one time by the author, which is not true. If the writer writes two packets of 110 bytes between two reads, then it is quite correct that the reader is reading 220 bytes.

If you only need to read one package at a time, you must make your packages self-describing. So, for example, the first four bytes contain the number of bytes. Then you can read a single packet by reading four bytes, converting that to an integer, and then reading that number of data bytes.

+6


a source


Your assumption that a read

will execute immediately after write

is not true. The write process can write to the pipe a couple of times before the read is read. The written data will be appended to the end of the buffer. In different ways, read and write are not batch oriented. They are flow oriented. This means that it write

just adds data to the buffer, it read

just gets whatever is available to it.



+1


a source


How do you sync with the author? You just need to read what you expect (specify 110 to read ())

0


a source







All Articles