如果第一個進程終止,則終止第二個(並行)進程

如果第一個進程終止,則終止第二個(並行)進程

假設我們有兩個並行運行的 shell 腳本

驅動程式.sh:

./proc1.sh&
./proc2.sh&

如果另一個進程以非零代碼退出,我該如何終止? (終止driver.sh)

答案1

使用 GNU Parallel 看起來像這樣:

parallel --halt now,fail=1 ::: script1.sh script2.sh

答案2

除非你在凋零進程中有一些邏輯來在某些狀態變化時控制另一個進程,否則你需要使用 PID 來追蹤/控制它們:

#!/bin/bash
./proc1.sh &
pid_1=$!  ## PID of proc1.sh

./proc2.sh &
pid_2=$!  ## PID of proc2.sh

while ps -p ${pid_1} &>/dev/null; do :; done ##Checking for existence of proc1.sh
kill ${pid_2}  ## Killing proc2.sh when proc1.sh is not running anymore

相關內容