[英]Exit all processes that shell started
我有一個簡單的bash腳本來運行給定數量的進程:
#!/bin/bash
# usage: ./run-abt.sh <agent count> <responder port> <publisher port>
echo "./abt-monitor 127.0.0.1 $2 $3 $1"
exec ./abt-monitor 127.0.0.1 $2 $3 $1 &
for (( i=1; i<=$1; i++ ))
do
echo "Running agent $i";
exec ./abt-agent 127.0.0.1 $2 $3 $i $1 > $i.txt &
done
我需要添加的是當用戶按下Ctrl+C
並控制返回到bash時,所有由run-abt.sh
創建的進程都將被殺死。
將此行添加到腳本的開頭:
trap 'kill $(jobs -p)' EXIT
當腳本從Control-C接收到中斷信號(或其他任何信號)時,它將在退出自身之前終止所有子進程。
在腳本末尾,添加一個調用以wait
以便腳本本身在后台進程完成之前自然退出),以便上面安裝的信號處理程序有機會運行。 那是,
for (( i=1; i<=$1; i++ ))
do
echo "Running agent $i";
exec ./abt-agent 127.0.0.1 $2 $3 $i $1 > $i.txt &
done
# There could be more code here. But just before the script would exit naturally,...
wait
使用內置的trap
:
trap handler_func SIGINT
但是,您必須分別存儲和管理子進程的pid。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.