Bash: Pipe output into background process?

2019-05-11 12:10发布

问题:

I would like to put a process into the background, and then pipe data to it multiple times. For example:

cat &                    # The command I want to write into
cat_pid=$!               # Getting the process id of the cat process

echo hello | $cat_pid    # This line won't work, but shows what I want to
                         #   do: write into the stdin of the cat process

So I have the PID, how can I write into that process? I would be open to launching the cat process in a different way.

Also, I'm on Mac, so I can't use /proc :(

回答1:

First, create a pipe:

$ mkfifo pipe

Second, start your cat process with input from the pipe:

$ cat <pipe &
[1] 4997

Now, send data to the pipe:

$ echo "this is a test" >pipe
$ this is a test


回答2:

mkfifo .pipe
cat < .pipe &
echo hello > .pipe