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

gfttwv5a  于 2022-12-13  发布在  Shell
关注(0)|答案(2)|浏览(344)

我想在进程之间进行同步。我的计算机有两个内核。用户可以从命令行输入模拟数。如果输入大于2,则第三个进程和其他进程必须等待,直到前面的进程之一完成。如果其中一个进程完成,则应启动下一个进程。例如,假设前两个进程已经在运行。第一个进程在第二个进程之前完成。现在第三个进程应该开始了。
我是新来的,我想出来了.反正是看到了:找不到命令。我该怎么做呢?下面是我的脚本:

#!/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
}
col17t5w

col17t5w1#

您可以使用waitbash中实现一种简单的进程同步方法,该方法等待一个或多个后台作业完成,然后再运行下一个作业。
您通常通过将&运算符附加到命令末尾来在后台运行作业。此时,新创建的后台进程的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秒。

  1. sleep 3将花费整整3秒来完成其执行
  2. sleep 4sleep 5都依次启动,运行max(4,5)大约需要5秒。
    你可以把类似的逻辑应用到你上面的问题上。希望这能回答你的问题。
zazmityj

zazmityj2#

您的代码还有许多其他问题,但答案是您应该在使用它之前声明anywait(因此在脚本中将其上移)。
请考虑使用http://www.shellcheck.net/,至少抑制脚本中最明显的错误。

相关问题