我想在进程之间进行同步,我的计算机有2个核心,用户可以从命令行输入仿真编号,如果输入大于2,则第3个和其余进程必须等到其中一个进程完成为止。如果其中一个完成,则应该执行下一个进程,例如,前两个进程已经在进行中,可以说,第一个已经在第二个进程之前完成了,现在应该执行第三个进程。可以看到没有找到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
}
您可以通过一种简单的过程同步方式,bash
使用wait
该方法等待一个或多个后台作业完成,然后再运行下一个。
通常,您可以通过在&
命令末尾附加运算符来在后台运行作业。该点处的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
您可以看到该脚本花了大约8秒钟才能运行完毕。时间的细分是
sleep 3
将花费整整3秒钟来完成其执行
sleep 4
并且sleep 5
都依次一个接一个地开始,并且花费了大约5秒的max(4,5)来运行。
您可以对上述问题应用类似的逻辑。希望这能回答您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句