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

后端 未结 2 1099
暗喜
暗喜 2021-01-13 01:52

I have a Bash script (Bash 3.2, Mac OS X 10.8) that invokes multiple Python scripts in parallel in order to better utilize multiple cores. Each Python script takes a really

相关标签:
2条回答
  • 2021-01-13 02:08

    Your trap looks 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
    $
    
    0 讨论(0)
  • 2021-01-13 02:11

    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!"
    
    0 讨论(0)
提交回复
热议问题