bash中的IPC(使用命名管道,不使用expect)
我正在编写一个bash脚本,它应该与现有的(perl)程序交互(交互式).不幸的是我无法触及现有的perl程序,也无法使用
expect.
目前,该脚本与此stackoverflow应答Is it possible to make a bash shell script interact with another command line program?的行一致 问题是(读:似乎是)perl程序并不总是发送< newline>在要求输入之前.这意味着bash的while …读取命名管道不会“获取”(读取:显示)perl程序的输出,因为它一直等待更多.至少这是我理解它的方式. 所以基本上perl程序正在等待输入但是用户不知道因为屏幕上没有任何内容. 所以我在bash脚本中做的是关于 #!/bin/bash mkfifo $readpipe mkfifo $writepipe [call perl program] < $writepipe &> $readpipe & exec {FDW}>$writepipe exec {FDR}<$readpipe ... while IFS= read -r L do echo "$L" done < $readpipe 这是有效的,除非perl程序正在做类似的事情 print "n"; print "Choose action:n"; print "[A]: Action A [B]: Action Bn"; print " [C]: canceln"; print " ? "; print "[C] "; local $SIG{INT} = 'IGNORE'; $userin = <STDIN> || ''; chomp $userin; print "n"; 然后bash脚本只“看到” Choose action: [A]: Action A [B]: Action B [C]: cancel 但不是 ? [C] 这不是最有问题的案例,而是最容易描述的案例. 有没有办法确保? [C]也被打印出来了(我和猫一起玩了< $readpipe& ;;但那真的不起作用)? 或者是否有更好的方法(鉴于我无法修改perl程序的限制,也不能使用expect)? 解决方法
使用读-N1.
让我们尝试下面的示例:与发送提示的程序交互(不是由换行符结束),我们的系统必须发送一些命令,接收发送的命令的回显.也就是说,子进程的总输出是: $cat example prompt> command1 prompt> command2 该脚本可能是: #!/bin/bash # cat example | while IFS=$' ' read -N1 c; do case "$c" in ">") echo "received prompt: $buf" # here,sent some command buf="" ;; *) if [ "$c" == $'n' ]; then echo "received command: $buf" # here,process the command echo buf="" else buf="$buf$c" fi ;; esac done 产生以下输出: received prompt: prompt received command: command1 received prompt: prompt received command: command2 第二个例子更接近原始问题: $cat例子 Choose action: [A]: Action A [B]: Action B [C]: cancel ? [C] 脚本现在是: #!/bin/bash # while IFS=$' ' read -N1 c; do case "$c" in '?') echo "*** received prompt after: $buf$c ***" echo '*** send C as option ***' buf="" ;; *) buf="$buf$c" ;; esac done < example echo "*** final buffer is: $buf ***" 结果是: *** received prompt after: Choose action:[A]: Action A [B]: Action B [C]: cancel ? *** *** send C as option *** *** final buffer is: [C] *** (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |