Why do we need two file descriptors when creating an unnamed pipe

Architecturepipe

I've been reading about unnamed pipes and as I understood them they're implemented as a buffer in memory. When creating the pipe I need to pass an array of size two and it returns two pointers (file descriptors) to the buffer. The index 0 is used for reading from the pipe and index 1 for writing to it.

My question is, if the buffer is just one and both indexes point to the same memory location and two processes can't read and write at the same time, then why do I need two file descriptors? I hope my question makes sense.

Best Answer

As stated by @MelBoyce in his comment, this is because of the conceptual nature of a pipe. It has a input and an output, and you read the bytes from the output in the exact same order they were written into the input. Pipes are not common files or pointers, you're not suppose to read and write anywhere in it. You're forced to read the first bytes that entered the pipe and that never be read yet.

Pipes may be implemented as a buffer in memory, but the implementation could vary if in the future, if another more efficient way to do it is invented for example. However, the conceptual nature of the pipe won't change. You'll still use the same read(1) and write(1) system calls and they still behave the same. The file descriptors you get when you call pipe(1) are used to force you to use the pipe correctly (and additionally provide some access control). That way, future modifications in the implementation won't break your code.

Related Question