Bash - 在读取输出的同时执行后台进程

Bash - 在读取输出的同时执行后台进程

我正在尝试启动一个进程 ( target_executable) 并让它在后台运行。我知道我可以通过以下方式做到这一点./target_executable &,但在运行该节目的 bash 脚本中,我想读取进程的输出以查找特定的输出。然后一旦输出是 .发现,我想让脚本完成,同时目标进程在后台运行。

这是我到目前为止所做的,但有很多问题(它没有在后台运行该进程,并且即使找到 ID,它也永远不会达到“完成阅读”):

echo "Starting Process..."
TARGET_ID=""
./target_executable | while read -r line || [[ "$TARGET_ID" == "" ]] ; do
    TARGET_ID=$(echo "$line" | grep -oE 'Id = [0-9A-Z]+' | grep -oE '[0-9A-Z]{10,}')

    if [ "$TARGET_ID" != "" ]
    then
        echo "Processing $line '$TARGET_ID'"
    fi
done
echo "Finished Reading..."

有什么想法吗?

答案1

这看起来像是一份工作coproc。来自帮助:

coproc: coproc [NAME] command [redirections]
    Create a coprocess named NAME.

    Execute COMMAND asynchronously, with the standard output and standard
    input of the command connected via a pipe to file descriptors assigned
    to indices 0 and 1 of an array variable NAME in the executing shell.
    The default NAME is "COPROC".

所以它看起来像:

echo "Starting Process..."
TARGET_ID=""
coproc (trap '' PIPE; ./target_executable < /dev/null & disown) # since it's in the bg, input won't be useful
while read -r line || [[ "$TARGET_ID" == "" ]] ; do
    TARGET_ID=$(echo "$line" | grep -oE 'Id = [0-9A-Z]+' | grep -oE '[0-9A-Z]{10,}')

    if [ "$TARGET_ID" != "" ]
    then
        echo "Processing $line '$TARGET_ID'"
        break
    fi
done <&${COPROC[0]} # redirect in from coprocess output

请注意,bash 为协进程的输入/输出设置了一个管道,因此应用程序必须能够处理损坏的输出管道。并非所有命令都可以。 (这就是为什么我被困SIGPIPE在子shell中。)

相关内容