在无限while循环中从管道输入中读取行

Posted

技术标签:

【中文标题】在无限while循环中从管道输入中读取行【英文标题】:Reading lines from piped input in infinite while loop 【发布时间】:2013-02-08 17:34:00 【问题描述】:

我在 bash 中制作了一个简单的脚本来充当 http 代理。

#!/usr/bin/env bash

trap "kill 0" SIGINT SIGTERM EXIT  # kill all subshells on exit

port="6000"

rm -f client_output client_output_for_request_forming server_output
mkfifo client_output client_output_for_request_forming server_output  # create named pipes

# creating subshell
(
    cat <server_output |
    nc -lp $port |  # awaiting connection from the client of the port specified
    tee client_output |  # sending copy of ouput to client_output pipe
    tee client_output_for_request_forming # sending copy of ouput to client_output_for_request_forming pipe
) &   # starting subshell in a separate process

echo "OK!"

# creating another subshell (to feed client_output_for_request_forming to it)
(
    while read line;  # read input from client_output_for_request_forming line by line
    do
        echo "line read: $line"
        if [[ $line =~ ^Host:[[:space:]]([[:alnum:].-_]*)(:([[:digit:]]+))?[[:space:]]*$ ]]
        then
            echo "match: $line"
            server_port=$BASH_REMATCH[3]  # extracting server port from regular expression
            if [[ "$server_port" -eq "" ]]
            then
                server_port="80"
            fi
            host=$BASH_REMATCH[1]  # extracting host from regular expression
            nc $host $server_port <client_output |  # connect to the server
            tee server_output  # send copy to server_output pipe
            break
        fi
    done

) <client_output_for_request_forming


echo "OK2!"

rm -f client_output client_output_for_request_forming server_output

我在第一个终端启动它。它输出OK!

然后在第二个中输入:

netcat localhost 6000

然后开始输入文本行,希望它们显示在第一个终端窗口中,因为有一个循环while read line。但是什么都没有显示。

我做错了什么?我怎样才能让它发挥作用?

【问题讨论】:

尝试同时使用-l-pnc 时应该会出错。 【参考方案1】:

如果没有进程正在从client_output fifo 读取,则后台管道未启动。由于读取client_output 的进程在从client_output_for_request_forming 读取一行之前不会启动,因此您的进程被阻塞。

【讨论】:

tee client_output_for_request_forming 放在tee client_output 之前会解决问题吗?

以上是关于在无限while循环中从管道输入中读取行的主要内容,如果未能解决你的问题,请参考以下文章

在while循环中从用户输入中获取最小值

openmp - 用于文本文件读取和使用管道的 while 循环

在while循环中使用scanf进行无限循环

shell:逐行读取文件内容

C Linux 编程 - 管道使子进程退出

C : while( scanf("%d",&num) != 1 ) 无限循环