How do I redirect stdout from one process to be read as file descriptor 3 in another?

99封情书 提交于 2019-12-24 13:06:59

问题


I want to redirect (stdout,stderr) from one process to (stdin,file descriptor 3) of another. How do I do that?

For example, if I have myscript.sh:

#!/bin/sh
# myscript.sh
echo "stdout"
echo "stderr" >&2

And reader.sh:

#!/bin/sh
# reader.sh
read key
echo "stdin: $key"
read key <&3
echo "fd3: $key"

How do I pipe the output of myscript.sh to reader.sh such that the final output is:

stdin: stdout
fd3: stderr

The closest I've gotten is:

./myscript.sh 2>&3 | ./reader.sh

But that hangs waiting for input (from fd 3)


回答1:


I would do this with a named pipe:

mkfifo err 
./myscript.sh 2>err | ./reader.sh 3<err

Doing 2>&3 in your attempt just sends stderr to wherever the parent shell has 3 pointed, and will fail if you haven't already opened 3 in that shell. It doesn't do any good for the reader shell's 3; even if inherited, it would be as a write fd, not a read one.



来源:https://stackoverflow.com/questions/19715318/how-do-i-redirect-stdout-from-one-process-to-be-read-as-file-descriptor-3-in-ano

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!