等待一个进程完成并执行另一个进程

时间:2016-05-13 08:28:36

标签: linux bash shell ubuntu

我想在进程之间进行同步。我的计算机有2个核心。用户可以从命令行输入模拟号。如果输入大于2,则第3个和其余进程必须等到其中一个进程如果其中一个完成,则应该执行下一个进程。例如,前两个进程已经在进行,让我们说,第一个进程在第二个进程之前完成。现在应该执行第三个进程。我是bash的新手,我想通了。可以看到anywait:命令未找到。我怎么能这样做?这是我的剧本:

#!/bin/bash
# My first script

count=2
echo -n "Please enter the number of simulation :"
read number
echo "Please enter the algorithm type  "
printf "0 for NNA\n1 for SPA\n2 for EEEA :"

while read type; do
    case $type in
        0 ) cd /home/cea/Desktop/simulation/wsnfuture 
        taskset -c 0 ./wsnfuture -u Cmdenv omnetpp.ini > /home/cea/Desktop/simulation/RESULTS/NNA/NNA0/0 &
        taskset -c 1 ./wsnfuture -u Cmdenv omnetpp.ini > /home/cea/Desktop/simulation/RESULTS/NNA/NNA0/1 &
        while [ $count -lt $number ]; do
        anywait
            cd /home/cea/Desktop/simulation/wsnfuture 
        mkdir /home/cea/Desktop/simulation/RESULTS/NNA/NNA$count
        taskset -c $((count % 2)) ./wsnfuture -u Cmdenv omnetpp.ini > /home/cea/Desktop/simulation/RESULTS/NNA/NNA$count/$count &
            count=$((count + 1))
        done 
        ;;
        1 ) while [ $count -lt $number ]; do
            cd /home/cea/Desktop/simulation/wsnfuture1
        taskset -c $((count % 2)) ./wsnfuture -u Cmdenv omnetpp.ini > /home/cea/Desktop/simulation/RESULTS/SPA/$count &
            count=$((count + 1))
        done 
        ;;
        2 ) while [ $count -lt $number ]; do
            cd /home/cea/Desktop/simulation/wsnfuture2
        taskset -c $((count % 2)) ./wsnfuture -u Cmdenv omnetpp.ini > /home/cea/Desktop/simulation/RESULTS/EEEA/$count &
            count=$((count + 1))
        done 
        ;;
        * ) echo "You did not enter a number"
        echo "between 0 and 2."
        echo "Please enter the algorithm type  "
        printf "0 for NNA\n1 for SPA\n2 for EEEA :"

    esac

done

function anywait(){
 while ps axg | grep -v grep | grep wsnfuture> /dev/null; do sleep 1; done
} 

2 个答案:

答案 0 :(得分:11)

您可以使用bashwait中实现一种简单的流程同步方式,等待一个或多个后台作业在运行下一个之前完成。

您通常通过将&运算符附加到命令的末尾来在后台运行作业。此时,新创建的后台进程的PID(进程ID)存储在特殊的bash变量中:$!wait命令允许在运行下一条指令之前终止此进程

这可以通过一个简单的例子来证明

$ cat mywaitscript.sh

#!/bin/bash

sleep 3 &

wait $!     # Can also be stored in a variable as pid=$!

# Waits until the process 'sleep 3' is completed. Here the wait on a single process is done by capturing its process id

echo "I am waking up"

sleep 4 &
sleep 5 &

wait                    # Without specifying the id, just 'wait' waits until all jobs started on the background is complete.

echo "I woke up again"

命令输出

$ time ./mywaitscript.sh
I am waking up
I woke up again

real    0m8.012s
user    0m0.004s
sys     0m0.006s

你可以看到脚本已经花了〜8s才能完成运行。时间的细分是

  1. sleep 3将花费3到3来完成执行

  2. sleep 4sleep 5都是接下来一个接一个地开始,并且它已经采用了最大值(4,5),大约是5秒才能运行。

  3. 您可以对上述问题应用类似的逻辑。希望这能回答你的问题。

答案 1 :(得分:0)

您的代码还有许多其他问题,但答案是您应该在使用之前声明anywait(在脚本中将其移动)。

请考虑使用http://www.shellcheck.net/来至少抑制脚本中最明显的错误/错误。