Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using unix pipes (in C) does the OS balance every write() with a read() or does it balance the total number of bytes?

Tags:

c

unix

pipe

for example, i want to get an array of 4 ints from child to parent. parent calls

read(apipe, buf, sizeof(int)*4);

child calls

for(int i=0; i<4;i++)
    write(bpipe, &array[i], sizeof(int));

does this do what I intend (getting 4 ints to the parent) or does the parent simply get the first integer?

I tried searching for this answer elsewhere, but either I don't know how to search or this is too subtle (or on the other hand too seemingly obvious) for literature to dwell on it much.

EDIT: To clarify further, I was trying to write a 4-part message and read all 4 parts in one read(). See comments on accepted answer.

like image 613
Dmitri Avatar asked Oct 09 '22 20:10

Dmitri


1 Answers

read and write work with bytes, not messages. For details of how they behave with pipes, see the documentation in POSIX:

  • http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html
  • http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html

In your code, I think the read should always get 4 ints, due to:

Upon successful completion, where nbyte is greater than 0, read() shall mark for update the last data access timestamp of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data.

There will always be 4 ints available for reading, because 4*sizeof(int) < PIPE_BUF and thus writes of this size are atomic.

It's possible that the allowance for read to return a short read when interrupted by a signal could come into play, but that should not be able to happen (in the real world, at least) when sufficiently many bytes are available immediately.

like image 181
R.. GitHub STOP HELPING ICE Avatar answered Oct 15 '22 10:10

R.. GitHub STOP HELPING ICE