简体   繁体   English

退出shell启动的所有进程

[英]Exit all processes that shell started

I have a simple bash script to run a given number of processes: 我有一个简单的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

What I need to add is when user press Ctrl+C and control returns to the bash, all processes created by run-abt.sh to kill. 我需要添加的是当用户按下Ctrl+C并控制返回到bash时,所有由run-abt.sh创建的进程都将被杀死。

Add this line to the beginning of your script: 将此行添加到脚本的开头:

trap 'kill $(jobs -p)' EXIT

When your script receives the interrupt signal from the Control-C (or any other signal, for that matter), it will terminate all the child processes before exiting itself. 当脚本从Control-C接收到中断信号(或其他任何信号)时,它将在退出自身之前终止所有子进程。

At the end of the script, add a call to wait so that the script itself exit naturally) before the background processes complete, so that the signal handler installed above has a chance to run. 在脚本末尾,添加一个调用以wait以便脚本本身在后台进程完成之前自然退出),以便上面安装的信号处理程序有机会运行。 That is, 那是,

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         

Use the trap builtin: 使用内置的trap

trap handler_func SIGINT

You'll have to store and manage the pids of the child processes separately, though. 但是,您必须分别存储和管理子进程的pid。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM