nd9*_*d97 5 bash file-descriptors netcat
一开始,我创建了一个小型服务器,netcat它运行良好:
#!/bin/bash
PORT="1234";
startServer(){
fifo="fifo/$1";
mkfifo "$fifo";
connected="0";
netcat -q 0 -l -p "$PORT" < "$fifo" | while read -r line; do
if [ "$connected" == "0" ];then
#listen for a new connection
startServer $(($1+1))&
connected="1";
fi
#server logic goes here
done > "$fifo";
rm "$fifo";
}
mkdir fifo;
startServer 0;
Run Code Online (Sandbox Code Playgroud)
它使用 fifos 将主循环输出重定向回netcat.
每次调用都会startServer增加 的值$1并创建一个 fifo 文件fifo/$1。
但我想使用bash 的自动文件描述符创建来摆脱fifo文件和startServer.
经过多次尝试,这是我目前修改startServer函数的尝试。我可以从客户端接收线路,但不幸的是它没有收到任何回复。我对出了什么问题感到困惑。
startServer(){
connected="0";
#create file descriptor and read output from main loop
exec {fd}> >( netcat -q 0 -l -p "$PORT" | while read -r line; do
if [ "$connected" == "0" ];then
#listen for a new connection
startServer&
connected="1";
fi
#server logic goes here
done ) >&$fd;
#close file descriptor
exec {fd}<&-;
exec {fd}>&-;
}
Run Code Online (Sandbox Code Playgroud)
另外,我不能使用 netcat 的“-e”选项,因为它在 netcat-openbsd 包中不可用。
不能fd在同一个命令中设置和使用;你正在有效地做exec {fd}> ... >&$fd。可以工作的是首先创建 bash fifo/pipe,使用一些简单的命令,如:. 例如:
startServer(){
local connected=0 fd
exec {fd}<> <(:)
nc -q 0 -l -p "$PORT" <&$fd |
while read -r line
do if [ "$connected" == "0" ]
then startServer $(($1+1)) &
connected="1"
fi
echo server $1 logic goes here
done >&$fd
exec {fd}<&-
}
Run Code Online (Sandbox Code Playgroud)