【问题标题】:Use read builtin command to read from parent stdin while in a subshell在子 shell 中使用 read 内置命令从父标准输入读取
【发布时间】:2016-07-13 18:44:50
【问题描述】:

我的脚本正在启动一个子shell/后台命令来读取输入,然后做更多的工作:

#!/bin/bash

(
while true; do
    read -u 0 -r -e -p "test_rl> " line || break
    echo "line: ${line}"
done
) &

sleep 3600 # more work

有了上述内容,我什至没有得到提示。如果我在启动子 shell 之前 exec 3>&0 然后从描述符 3 (-u 3) 读取,那么我至少会得到提示,但读取命令仍然没有得到我输入的任何输入。

如何让 read 内置函数从终端(父级的标准输入文件描述符)正确读取?

【问题讨论】:

  • 请发布完整的例子
  • 后台进程不允许从终端读取。
  • 在man bash中查找协同进程
  • @cdarke 这是一个很好的指针。我没有提到的一件事是我实际上有两个不同的子shell(一个处理输入,另一个处理输出),显然你一次只能使用一个 coproc。尽管 thom 的建议似乎有效,但我可以有一个 coproc 处理输入和一个正常的 subshel​​l 处理输出。

标签: bash shell multiprocessing stdin


【解决方案1】:

如何让 read builtin 从终端正确读取 (父级的标准输入文件描述符)?

你可能想试试这个(使用父文件描述符):

#!/bin/bash

(
while true; do
    read -u 0 -r -e -p "test_rl> " line || break
    echo "line: ${line}"
done
)<&0 >&1 &

sleep 3600 # more work

【讨论】:

  • 行得通,谢谢。我不知道为什么有人投了你一票。
  • 我可以用函数做同样的事情吗?你能解释一下你在做什么吗?您将stdin 和stdout 从父进程重定向到子shell?
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2019-05-16
  • 2018-03-05
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
相关资源
最近更新 更多