I have code where I want to encapsulate a particular piece of code into a forked child so that if the code causes issues, it will not affect the parent and the parent will be able to report.
I am not execing after the fork call. Just plain fork and then the code runs that would have normally run in the parent.
The code in the child outputs stuff to stdout and stderr. Due to issues with interleaving output and stdio buffering, I was now looking into TLPI for a better solution.
The idea I came up with was roughly:
pipe()for each streamfork()- in child:
close()read end of pipesdup2()the write ends onto the file descriptors forstdoutandstderrrespectivelysetbuf(fd, NULL)to turn offstdiostream buffering inside the child.
- in parent:
close()write ends of pipes- use
select/pselect/epolletc (has to run across Linux, BSDs, AIX, Solaris etc) to watch the read ends of the pipes for new data and when it arriveswrite()it straight to the respective file descriptors in the parent process.
Now, I presume there is one step missing between the dup2 and the setbuf inside the child. What is it?
setbuf takes a FILE* whereas of course dup2 acts on int.
freopen came to mind, but it requires a path. If I merely want to assign a new fileno to the streams, how can I do that?