在单个队列上运行后台进程

时间:2015-07-16 19:31:49

标签: macos bash command queue background-process

在OS X上,我试图运行"说"命令作为后台进程在它们自己的队列中,与主进程分开,它只是回显语句。举个例子:

echo "hello"
say "hello" &       # first in queue

echo "and"          # this should be printed immediately after the first echo,
                    # without waiting for the say command to finish.
say "and" &         # begins as soon as the first say command is finished

echo "goodbye"      # should also be printed out immediately without waiting for any say command
say "goodbye" &     # begins as soon as second say command is finished

目前的问题是,say命令是异步运行的并且同时被说出。以下是我目前尝试解决的问题:

export v_queue=()
function q_push { v_queue=("${v_queue[@]}" $1); }
function q_shift { v_queue=(${v_queue[@]:1}); }

function speakbg {
    while (( ${#v_queue[*]} > 0 ))
    do
        wait ${v_queue[0]}
        q_shift
    done
    say "$*"
}

function speak {
    speakbg "$*" &    # desired result achieved by removing the '&', but the echos should be printed immediately!
    q_push $!
}


echo "hello"
speak "hello"
echo "and"
speak "and"
echo "goodbye"
speak "goodbye"

0 个答案:

没有答案