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.
read
and write
work with bytes, not messages. For details of how they behave with pipes, see the documentation in POSIX:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With