The main root problem seems to be the programmatic launch of an interactive terminal program.
Now this in my part will require actual testing, but you need approximately
(If you do not need to make a distinction between stdoutand stderr, you could just simplify your life using popen(3)- perhaps you can redirect stderrto the stdoutright command line choice).
However, for the correct working solution, I believe that you will probably need to use pseudo-ttys ( pty(7)), calling forkpty(3)instead of a simple fork., , C, . , expect - , pexpect. expect, -, C, libexpect(3), tcl/tk , , .