【问题标题】:Linux : launch a specific action when another process is terminatedLinux:当另一个进程终止时启动特定操作
【发布时间】:2017-12-29 12:48:24
【问题描述】:

我有一个脚本foo.sh 在后台启动bfoo.sh 的5 个进程,如下所示:

for i in {1..5}
do 
  ./bfoo.sh &
done 
wait 
echo ok

我是这样使用它的:

./foo.sh

在 for 循环之后的 foo.s 中,我想做类似的事情,即为每个进程 bfoo.sh 终止做

echo $PID_Terminated

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    为此,您需要存储bfoo.sh 的每个后台进程的PID。 $! 包含最后由 shell 后台处理的进程 ID。我们将它们一次添加到数组中,稍后对其进行迭代

    请记住,这将一个接一个地运行您的后台进程,因为您在每个进程 ID 上分别有 wait

    #!/usr/bin/env bash
    
    pidArray=()
    
    for i in {1..5}; do 
        ./bfoo.sh &
        pidArray+=( "$!" )
    done 
    

    现在循环等待每个进程

    for pid in "${pidArray[@]}"; do
        wait "$pid"
        printf 'process-id: %d finished with code %d\n' "$pid" "$?"
    done
    

    我另外添加了后台进程$?结束时的退出代码,以便可以调试任何异常退出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      相关资源
      最近更新 更多