Pipes and FIFOS
- Think water flowing
- there is an input end
- And an output end
- And data flows through
- Pipes are
- Unidirectional
- You can not lseek on a pipe
- A stream of data with no boundaries
- No message format, just raw data
- Read will block until at least one byte has been written
- when the write end is closed, and the last byte is read, they will return eof
-
int pipe(int pipefd[2]);
- The single parameter is an array of integers of size 2.
- This represents both the read end (0) and the write end(1) of the pipe.
- Data flows from fd[1] to fd[0]
- Return -1 on error.
- PIPE_BUF
- At least 512 bytes
- But defined in limits.h
- Messages of this size or smaller are atomic, ie will not be mixed.
- Messages larger than this may block
- Be chopped into smaller pieces
- May be intermingled in a multiple writer situation.
- May cause writing to bock.
-
int pipe2(int pipefd[2], int flags);
- flags can be
- 0 - behave like
pipe
- O_CLOEXEC
- O_DIRECT : Treat the pipe as a packet oriented object.
- read reads the next packet, if the size is smaller than the packet, the rest of the packet is discarded.
- So specify a size of PIPE_BUF for reads.
- O_NONBLOCK : don't block, return immediately if there is no data.
- A normal use scenario
- create a pipe.
- fork
- ON the reader end
- Close file descriptor 0
- dup the read end of the pipe.
- Close the write end of the pipe.
- Read from stdin.
- On the writer end
- close file descriptor 1
- dup the write end of the pipe.
- close the read end of the pipe.
- Write to the stdout.
- Note: Processes using the pipe process must be related (through a common ancestrial fork).
- See pipe1.cpp for a simple demo.
- See pi.cpp for a more complex demo.