[TUHS] First appearance of named pipes

arnold at skeeve.com arnold at skeeve.com
Wed Mar 11 17:02:59 AEST 2020


Hi Grant.

Grant Taylor via TUHS <tuhs at minnie.tuhs.org> wrote:

> The larger more onerous question is could I leverage exec to alter where 
> file descriptors 0 (STDIN), 1 (STDOUT), and 2 (STDERR) are set to, 
> including changing 1 to the value of a FIFO, and 0 of a subsequent 
> command to also be the value of the FIFO, thus have pipe like behavior 
> between two commands without using a pipe or redirection as in ">".

There's nothing preventing you from doing that. After the fork() and
before the exec(), just close() and dup() the relevant fds in the right
order and you're set.

> This has also gotten me to wonder about the possibility of having 
> multiple commands output to a file descriptor; 1 / 2 / other, that is 
> input to a separate command.  Sort of the opposite of tee, in a manner 
> of speaking.  I'll try to articulate:
>
> $ mkfifo test.fifo
> $ exec 3>&1
> $ exec 1> test.fifo
> $ for l in {a..z}; do echo $l; sleep 1; done &
> $ for L in {A..Z}; do echo $L; sleep 1; done &
> $ for n in {1..100}; do echo $n; sleep 1; done &
> $ exec 1>&3
> $ cat test.fifo

I don't think that this is any different from:

	(for l in {a..z}; do echo $l; sleep 1; done &
	 for L in {A..Z}; do echo $L; sleep 1; done &
	 for n in {1..100}; do echo $n; sleep 1; done &) | cat

which reduces to:

	(for l in {a..z}; do echo $l; sleep 1; done &
	 for L in {A..Z}; do echo $L; sleep 1; done &
	 for n in {1..100}; do echo $n; sleep 1; done &) > /some/file

(You might want to background that whole mess given that the final
pipeline will sleep for 100 seconds.)

> This seems special to me in that I have three processes (for loops) 
> writing into what is effectively the same pipe.

It's not any different than calling `stty -tostop' and then simply
backgrounding the three loops at the terminal.  Try it!

(This is the beauty of the Unix model, an fd is just a data sink,
we don't care where it goes.)

> I would be very eager to learn from anyone who is willing to teach me 
> pointers.  :-)

At the cost of tooting my own horn, I recommend my book "Linux Programming
by Example: The Fundamentals", which, despite the "Linux" in the title,
covers basic Unix programming, including file descriptor manipulation
of the sort under discussion here.

HTH,

Arnold


More information about the TUHS mailing list