Bidirectional pipe experiment
Fri, 20 Nov 26 12:25:10 CETPlan 9 pipes can be bidirectional! To showcase that, I did a small experiment that I want to share.
The experiment is built from two programs, a and b.
a is the “receiver”, b is the “sender” or data source.
The programs are run in a pipe like this: a | b.
Since the standard IO pipe between those programs is bidirectional, we do something pretty uncommon:
We use the standard output file descriptor 1 of a as an input to read from, and the standard input fd 0 of b as an output to write to.
The mkfile looks like this:
</$objtype/mkfile
TARG=a b
</sys/src/cmd/mkmany
Like mentioned, a.c needs to open fd 1 for read:
#include <u.h>
#include <libc.h>
#include <bio.h>
void
main(int, char**)
{
Biobuf *bin;
char *s;
bin = Bfdopen(1, OREAD);
if (!bin)
sysfatal("Bfdopen: %r");
while (s = Brdstr(bin, '\n', 1)) {
fprint(2, "a got: %s\n", s);
free(s);
}
Bterm(bin);
exits(nil);
}
And b.c:
#include <u.h>
#include <libc.h>
#include <bio.h>
void
main(int, char**)
{
Biobuf *bout;
int i;
bout = Bfdopen(0, OWRITE);
if (!bout)
sysfatal("Bfdopen: %r");
for (i = 0; i < 10; i++) {
Bprint(bout, "%d (from b)\n", i);
}
Bterm(bout);
exits(nil);
}
If we run it:
; a | b
a got: 0 (from b)
a got: 1 (from b)
a got: 2 (from b)
a got: 3 (from b)
a got: 4 (from b)
a got: 5 (from b)
a got: 6 (from b)
a got: 7 (from b)
a got: 8 (from b)
a got: 9 (from b)
Note that even though this is supported, I don't think I've seen this in use anywhere in the Plan 9 code base.
Comment: Fediverse Post