简体   繁体   中英

how can I make bash block on getting a line of stdout from a job that I have spawned

I need to launch a process within a shell script. (It is a special logging process.) It needs to live for most of the shell script, while some other processes will run, and then at the end we will kill it.

A problem that I am having is that I need to launch this process, and wait for it to "warm up", before proceeding to launch more processes.

I know that I can wait for a line of input from a pipe using read , and I know that I can spawn a child process using & . But when I use them together, it doesn't work like I expect.


As a mockup:

When I run this (sequential):

(sleep 1 && echo "foo") > read

my whole shell blocks for 1 second, and the echo of foo is consumed by read, as I expect.

I want to do something very similar, except that I run the "foo" job in parallel:

(sleep 1 && echo "foo" &) > read

But when I run this, my shell doesn't block at all, it returns instantly -- I don't know why the read doesn't wait for a line to be printed on the pipe?

Is there some easy way to combine "spawning of a job" ( & ) with capturing the stdout pipe within the original shell ?


An example that is very close to what I actually need is, I need to rephrase this somehow,

(sleep 1 && echo "foo" && sleep 20 &) > read; echo "bar"

and I need for it to print "bar" after exactly one second, and not immediately, or 21 seconds later.

Here's an example using named pipes, pretty close to what I used in the end. Thanks to Luis for his comments suggesting named pipes.

#!/bin/sh

# Set up temporary fifo
FIFO=/tmp/test_fifo
rm -f "$FIFO"
mkfifo "$FIFO"

# Spawn a second job that writes to FIFO after some time
sleep 1 && echo "foo" && sleep 20 >$FIFO &

# Block the main job on getting a line from the FIFO
read line <$FIFO

# So that we can see when the main job exits
echo $line

Thanks also to commenter Emily E., the example that I posted that was misbehaving was indeed writing to a file called read instead of using the shell-builtin command read .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM