Yes, I can’t. It seems weird ostream has no close, since istream can detect end of file.
Here’s my situation: I am capturing all the output on Posix fd2, in this process, and its children, by creating a pipe and dup2’ing the pipe output end onto fd2. A thread then reads the read end of the pipe using an associated C stream (and happens to write each line with a timestamp to the original fd2 via another associated C stream).
When all the children are dead, I write a closing message to cerr, then I need to close it so the thread echoing it to the original error file will close the pipe and terminate.
The thread is not detecting eof(), even though I am closing both stderr and fd2.
I have duplicated my main program using a simple one, and using C streams instead of C++ iostreams, and everything works just fine by fclosing stderr (there are no child processes in that simplified test though).
Edit: hmm .. do I need to close the original pipe fd after dup2’ing it onto channel 2? I didn’t do that, so the underlying pipe still has an open fd attached. Aha .. that’s the answer!
When you duplicate a file descriptor with
dup2the original descriptor remains a valid reference to the underlying file. The file won’t be closed and the associated resources freed until all file descriptors associated with a particular file are closed (withclose).If you are using
dup2to copy a file descriptor to a well known number (such as 2 forstderr), you usually want to callcloseon the original file descriptor immediately after a successfuldup2.