background process pipe-input

if i want to display “aaa” on screen:

(1)$: echo aaa | cat                 ... works OK
(2)$: echo aaa | ( cat )             ... works OK
(3)$: echo aaa | ( cat & )           ... NOT working
(4)$: ( echo aaa & ) | cat           ... works OK 
(5)$: echo aaa | ( cat <&0 & )       ... works ok in BASH (but not in SH)
(6)$: echo aaa | ( cat <&3 & ) 3<&0  ... works ok in BASH and SH

conlusion from (3) and (4) -> detached process still have connected output that can be controlled, used, redirected…, but not input!

My question is: does someone understand why and how line (5) works ???

… “<&0” is short for “0<&0”, why redirecting 0 to 0 is solution, and what really happens behind with input of detached process. Subshell’s are not the problem, using braces {…} instead of (…) provide same results.

… and question2: is there better solution for “giving input to detached process” than line (6).

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes, as required by POSIX, commands started in background with & have their standard input redirected from /dev/null.

And indeed

{ cmd <&3 3<&- & } 3<&0

is the most obvious way to work around it.

It’s not clear why you’d want to run part of pipeline in background though.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments