Bash script kill background (grand)children on Ctrl+C

时光毁灭记忆、已成空白 提交于 2019-12-01 06:07:53

I got it! All you have to do is get rid of that python SIGINT handler.

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!"

Your trap look good to me:

$ bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin11)
Copyright (C) 2007 Free Software Foundation, Inc.

$ cat ./thang 
#! /bin/bash
set -e

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

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

function killstuff {
  jobs -p | xargs kill
}

trap killstuff SIGINT

process one
process two
wait

$ ./thang 
Tick from one
Tick from two
Tick from one
Tick from two
^C$ ps aux | grep python | grep -v grep
$
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!