In some systems, pipes may be bi-directional. But they should not be, and any assumption that they will not be tolerated. In particular, they are not on Linux.
Be that as it may, your code has a problem - both processes try to read and write to the same channel. The intended use for pipes is what the child writes and the parent reads, or vice versa. The current way that you do all this works for you right now, because you read and write once and wait
for the child. But when you execute a cycle trying to do what you are doing, you cannot wait
- and without synchronization, the child will often (but not always!) End up reading what he intended to send to his parents, and vice versa.
If you need data going in both directions, you can use two pairs of pipes. Name them parent_pipe
and child_pipe
. The parent would read from parent_pipe[0]
and write to child_pipe[1]
, and the child would read from child_pipe[0]
and write to parent_pipe[1]
.
#include<unistd.h>
Alternatively, you can use a pair of UNIX sockets created using socketpair(AF_LOCAL, SOCK_STREAM, 0, sockdes)
(where sockdes
is what we renamed pipdes
to, since it is now sockets, not pipes). The child will read and write to sockdes[0]
, and the parent will read and write to sockdes[1]
. Or vice versa.
cHao
source share