I am working on a program where the main program forks itself and the child process calls exec. I have set it up so that the parent process has 2 pipes StdOutPipe and StdInPipe, and the child process calls dup so that stdout writes to the StdOutPipe and stdin reads from StdInPipe. Then the parent process calls wait, after which i would like to read the entirety of the StdOutPipe into a buffer. I know you can do so by reading one character at a time, but is there a faster way to do so?
>Solution :
For performance reasons, one typically reads a chunk at a time, not a character at a time.
- Loop,
- Attempt to enlarge the buffer so it can fit CHUNK_SIZE more bytes.
- If an error occurred,
- Fail.
- Attempt to read CHUNK_SIZE bytes from the pipe into the unused part of the buffer.
- If an error occurred,
- Fail.
- If EOF was reached,
- Break.
- Increased the total number of bytes read by the number of bytes read.