Suppose I have some process that when ready will output to
stdout
. Even though I want my script to run asynchronously with respect to that process, I still want the script to block and wait on that first line. Modelled bellow with sleep
and echo
is exactly the behaviour I need in working order:
coproc monitor {
sleep 2
echo "init"
sleep 1
echo "foo"
echo "bar"
echo "baz"
}
read -u ${monitor} line
echo started
exec 3<&${monitor}
cat <&3 &
sleep 2
The script starts and creates the coprocess, then it waits on that first line via read -u
, and finally it attaches 3
to ${monitor}
so that we can then use cat
in yet another background process to pipe stuff from monitor to actual stdout
.
Thus we get:
# waits 2 seconds
started
# after 1 second:
foo
bar
baz
I am not too happy with these two lines though
exec 3<&${monitor}
cat <&3 &
Is there no better way of achieving this? It seems like a rather roundabout of doing things. But everything I tried hasn't worked.
For example cat <&"${monitor}"
works, but then it blocks the script. { cat <&"${monitor}" ; } &
gives Bad file descriptor
for reasons I don't understand (but even then, I am still suing yet another background process, which seems sily).
Asked by Mathias Sven
(273 rep)
May 27, 2025, 06:11 PM
Last activity: May 28, 2025, 04:11 PM
Last activity: May 28, 2025, 04:11 PM