将stdout传递到另一个进程的文件描述符 [英] Pipe stdout to another process's file descriptor
问题描述
到目前为止,这已经挫败了我.我知道如何在同一过程中将我的标准输出重定向到另一个文件描述符.我知道如何将stdout传递到另一个进程的stdin.但是,如果我想将一个进程的stdout通过管道传送到另一个进程中的文件描述符,该怎么办?具体来说,对于while读取的情况...
This one is foiling me so far. I know how to redirect my stdout to another file descriptor in the same process. I know how to pipe stdout to another process's stdin. But what if I want to pipe a process's stdout to a file descriptor in another process?? Specifically, for the case of while read...
cat file | while read -u 9 line; do //some stuff; done
如何将cat的输出输出到while循环的文件描述符9中?
How do I get cat's output onto file descriptor 9 of the while loop?
推荐答案
管道在标准输入和输出(文件描述符0和1)下专门用于 ;它们不会推广到其他描述符.使用进程替换和输入重定向代替.
Pipes work specifically with standard input and output (file descriptors 0 and 1); they don't generalize to other descriptors. Use process substitution and input redirection instead.
while read -u 9 line; do
...
done 9< <(cat file)
当然,您不应像这样使用 cat
;只需使用常规的输入重定向
Of course, you shouldn't use cat
like this; just use regular input redirection
while read -u 9 line; do
...
done 9< file
奖金,符合POSIX的答案:使用命名管道.
Bonus, POSIX-compliant answer: use a named pipe.
mkfifo p
cat file > p &
while read line <&9; do
...
done 9< p
这篇关于将stdout传递到另一个进程的文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!