2013-02-08 98 views
0

我在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!

和在第二I型:

netcat localhost 6000 

,然後開始輸入期望是有周期while read line它們被顯示在第一個終端窗口的文本行。但沒有顯示。

這是什麼,我做錯了?我怎樣才能使它工作?

+0

您應該在嘗試同時使用'-l'和'-p'與'nc'的時候出現錯誤。 – chepner 2013-02-08 21:06:59

回答

3

如果沒有進程正在從client_output fifo讀取,那麼後臺管道未啓動。由於讀取client_output的進程在從client_output_for_request_forming讀取一行之前不會啓動,因此您的進程被阻止。

+0

在'tee client_output'之前將'tee client_output_for_request_forming'解決問題嗎? – ovgolovin 2013-02-08 18:10:21