UNIX FAQ Version 2.1 92/12/04 -- Question 4.5

UNIX FAQ Version 2.1 92/12/04 -- Question 4.5

How do I use popen() to open a process for reading AND writing?

The problem with trying to pipe both input and output to an arbitrary slave process is that deadlock can occur, if both processes are waiting for not-yet-generated input at the same time. Deadlock can be avoided only by having BOTH sides follow a strict deadlock-free protocol, but since that requires cooperation from the processes it is inappropriate for a popen()-like library function.

The 'expect' distribution includes a library of functions that a C programmer can call directly. One of the functions does the equivalent of a popen for both reading and writing. It uses ptys rather than pipes, and has no deadlock problem. It's portable to both BSD and SV. See the next answer for more about 'expect'.