有没有办法让子进程的输出(下面除了“睡眠”之外的东西)与前台命令循环的输出相吻合?例如:
while true
do
echo "updating screen..."
sleep 3 & # Replace with command which takes some time and updates the screen
read -s -n 1 -p "Input: " input
case "$input" in
q)
exit
;;
f)
echo 'foo'
;;
esac
done
答案1
shell 对多处理做出假设;第一个也是最重要的是:一个程序应该一次控制终端,否则输入(和输出)将会变得混乱。如果您放置的“睡眠”程序想要从终端获取输入怎么办?键盘输入发送到哪里?到子进程('sleep')还是到语句read
?
由此您需要假设子进程(“睡眠”)不会获得输入。您还必须等到命令循环(处理“q”或“f”)和子流程已完成。我建议编写除 shell 脚本之外的其他内容,例如 python,以绕过 shell 的假设;但正如我所展示的,它也可以在 Bourne(或 ksh、bash 或 zsh)shell 中完成。
#!/usr/bin/python
import os, select, subprocess, sys
devnull = open('/dev/null', 'a')
# this is the same as "sleep 3 </dev/null > pipefile &" but will handle
# processing output at the same time
p = subprocess.Popen(
['/bin/sh', '-c',
'i=0; while [ $i -lt 30 ]; do echo $i; sleep 2; i=`expr $i + 1`; done' ],
stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
command_done = False
try:
# endless loop until both input and output are done
while True:
inputs = []
# only send input to our command loop
if not command_done:
sys.stdout.write('Input: ')
sys.stdout.flush()
inputs.append(sys.stdin)
if p.returncode is None: # still not finished
p.poll()
inputs.append(p.stdout)
outputs = []
if not inputs and not outputs: # both are done
break # exit while loop
#print inputs, outputs
r, w, x = select.select(inputs, outputs, [])
#print 'r=', r, 'w=', w, 'x=', x
# input from the user is ready
for file in r:
if file is sys.stdin:
input = file.read(1)
if input == 'q':
command_done = True
if p.returncode is None:
os.kill(p.pid, 15)
elif input == 'f':
sys.stdout.write('foo\n')
# the subprocess wants to write to the terminal too
else:
input = file.readline()
sys.stdout.write(input)
finally:
if p.poll():
try:
print
os.kill(p.pid, 15)
except OSError:
pass
您可以在 shell 脚本中执行此操作,但输入/输出不会很好地集成。
#!/bin/bash
mkfifo /tmp/mergedout.p
( i=0; while [ $i -lt 30 ]; do echo $i; sleep `expr 30 - $i`; i=`expr $i + 1`; done ) </dev/null >/tmp/mergedout.p 2>&1 &
pid=$!
exec 3</tmp/mergedout.p
done=false
trap 'rm /tmp/mergedout.p' 0
while [ -n "$pid" -a $done = false ]; do
if [ $done = false ]; then
echo -n "Input: "
read -t 0.1 -s -r -n 1
case $REPLY in
q) done=true; if [ -n "$pid" ]; then kill $pid; fi;;
f) echo foo;;
esac
fi
if [ -n "$pid" ]; then
kill -0 $pid 2>&-
if [ $? -ne 0 ]; then
echo "$pid terminated"
wait $pid
pid=""
exec 3<&-
else
read -t 0.1 -u 3 -r
echo "reading from fd3: X${REPLY}X $?"
if [ -n "$REPLY" ]; then
echo "$REPLY"
fi
fi
fi
sleep 0.5
done
我自己,Python 更清晰,更“吻合”,但在大多数情况下,这些都可以通过任何一种方式完成。