哪里有需要,哪里就有办法!我认为这是一个很好的 bash 课程
流程管理和 IPC 是如何工作的。最好的解决方案当然是 Expect。
但真正的原因是管道可能很棘手,并且设计了许多命令
等待数据,这意味着该进程将成为僵尸,原因如下:
海湾很难预测。但是学习如何以及为什么会提醒我们什么是
在引擎盖下进行。
当两个进程参与对话时,危险在于一个或两个进程会
尝试读取永远不会到达的数据。参与规则必须是
晶莹剔透。诸如 CRLF 和字符编码之类的东西可以杀死聚会。
幸运的是,像 bash 脚本及其子进程这样的两个亲密伙伴是
相对容易保持一致。最容易错过的是 bash 是
为它所做的每一件事启动一个子进程。如果你能做到
使用 bash,您完全知道自己在做什么。
关键是我们想与另一个进程交谈。这是一个服务器:
# a really bad SMTP server
# a hint at courtesy to the client
shopt -s nocasematch
echo "220 $HOSTNAME SMTP [$$]"
while true
do
read
[[ "$REPLY" =~ ^helo\ [^\ ] ]] && break
[[ "$REPLY" =~ ^quit ]] && echo "Later" && exit
echo 503 5.5.1 Nice guys say hello.
done
NAME=`echo "$REPLY" | sed -r -e 's/^helo //i'`
echo 250 Hello there, $NAME
while read
do
[[ "$REPLY" =~ ^mail\ from: ]] && { echo 250 2.1.0 Good guess...; continue; }
[[ "$REPLY" =~ ^rcpt\ to: ]] && { echo 250 2.1.0 Keep trying...; continue; }
[[ "$REPLY" =~ ^quit ]] && { echo Later, $NAME; exit; }
echo 502 5.5.2 Please just QUIT
done
echo Pipe closed, exiting
现在,希望能发挥作用的脚本。
# Talk to a subprocess using named pipes
rm -fr A B # don't use old pipes
mkfifo A B
# server will listen to A and send to B
./smtp.sh < A > B &
# If we write to A, the pipe will be closed.
# That doesn't happen when writing to a file handle.
exec 3>A
read < B
echo "$REPLY"
# send an email, so long as response codes look good
while read L
do
echo "> $L"
echo $L > A
read < B
echo $REPLY
[[ "$REPLY" =~ ^2 ]] || break
done <<EOF
HELO me
MAIL FROM: me
RCPT TO: you
DATA
Subject: Nothing
Message
.
EOF
# This is tricky, and the reason sane people use Expect. If we
# send QUIT and then wait on B (ie. cat B) we may have trouble.
# If the server exits, the "Later" response in the pipe might
# disappear, leaving the cat command (and us) waiting for data.
# So, let cat have our STDOUT and move on.
cat B &
# Now, we should wait for the cat process to get going before we
# send the QUIT command. If we don't, the server will exit, the
# pipe will empty and cat will miss its chance to show the
# server's final words.
echo -n > B # also, 'sleep 1' will probably work.
echo "> quit"
echo "quit" > A
# close the file handle
exec 3>&-
rm A B
请注意,我们并不是简单地将 SMTP 命令转储到服务器上。我们检查
每个响应代码以确保一切正常。在这种情况下,事情不会
好的,脚本将退出。