如何杀死后,按Ctrl + C是由一个shell脚本打开的所有进程? [英] How to kill all processes that were opened by a shell script upon ctrl + C?

查看:412
本文介绍了如何杀死后,按Ctrl + C是由一个shell脚本打开的所有进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这是我从一个shell脚本集体启动一对夫妇的Python脚本如下:

 #!/斌/庆典
蟒蛇prog1.py&安培;
蟒蛇prog2.py&安培;
蟒蛇prog3.py

由于我开发我常常想停止这些进程。我通常按​​Ctrl + C这样做,但unfortuntaly一对夫妇的Python程序保持(zeromq)插槽开放。这意味着,然后我必须手动找到他们(我用的 lsof的-i 的),并使用PID杀死他们。

所以我在寻找自动从shell杀那些蟒蛇的过程,当我按Ctrl + C更简单的方法。在<一个href=\"http://stackoverflow.com/questions/11696691/bash-script-kill-background-grandchildren-on-ctrlc\">another这里线程#2 我发现了一些code据称应该做什么,我需要。我只是不明白有关code什么,我如何能调整到我的需要。

会有人这么好心帮我在这里?

 猫&GT; work.py&LT;&LT;'EOF'
进口SYS,时间,信号
signal.signal(signal.SIGINT,signal.SIG_DFL)
对于在范围I(10):
    time.sleep(1)
    打印蜱,sys.argv中[1]
EOF
搭配chmod + X work.py功能过程{
    蟒蛇./work.py $ 1
}过程中的一个&安培;
等待$!
回声完成!


解决方案

让bash脚本捕捉SIGINT,并将其杀死当前进程组中的所有内容:

  intexit(){
    #杀(当前进程组中的所有进程)的子进程
    杀-HUP - $$
}hupexit(){
    #HUP'd(可能是intexit)
    回声
    回声中断
    出口
}陷阱hupexit HUP
陷阱intexit INT蟒蛇prog1.py&安培;
蟒蛇prog2.py&安培;
蟒蛇prog3.py&安培;等待

I've got a couple python scripts which I start collectively from a shell script as follows:

#!/bin/bash
python prog1.py &
python prog2.py &
python prog3.py 

Since I am developing I often want to stop these processes. I normally do so by hitting ctrl+C, but unfortuntaly a couple python programs keep (zeromq) sockets open. This means I then have to manually find them (I use lsof -i), and kill them using the PID.

So I'm looking for an easier way of automatically killing those python processes from the shell when I hit ctrl+C. On another thread here on Stackoverflow I found some code which supposedly should do what I need. I just don't understand anything about the code and how I could adjust it to my needs.

Would anybody be so kind to help me out here?

cat >work.py <<'EOF'
import sys, time, signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
for i in range(10):
    time.sleep(1)
    print "Tick from", sys.argv[1]
EOF 
chmod +x work.py

function process {
    python ./work.py $1
}

process one &
wait $!
echo "All done!"

解决方案

Let the bash script catch SIGINT, and have it kill everything in the current process group:

intexit() {
    # Kill all subprocesses (all processes in the current process group)
    kill -HUP -$$
}

hupexit() {
    # HUP'd (probably by intexit)
    echo
    echo "Interrupted"
    exit
}

trap hupexit HUP
trap intexit INT

python prog1.py &
python prog2.py &
python prog3.py &

wait

这篇关于如何杀死后,按Ctrl + C是由一个shell脚本打开的所有进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆