How to send control+c from a bash script?

前端 未结 5 1672
孤街浪徒
孤街浪徒 2020-12-02 11:05

I\'m starting a number of screens in a bash script, then running django\'s runserver command in each of them. I\'d like to be able to programmatically stop them

5条回答
  •  离开以前
    2020-12-02 11:46

    ctrl+c and kill -INT are not exactly the same, to emulate ctrl+c we need to first understand the difference.

    kill -INT will send the INT signal to a given process (found with its pid).

    ctrl+c is mapped to the intr special character which when received by the terminal should send INT to the foreground process group of that terminal. You can emulate that by targetting the group of your given . It can be done by prepending a - before the signal in the kill command. Hence the command you want is:

    kill -INT -
    

    You can test it pretty easily with a script:

    #!/usr/bin/env ruby
    
    fork {
        trap(:INT) {
            puts 'signal received in child!'
            exit
        }
        sleep 1_000
    }
    
    puts "run `kill -INT -#{Process.pid}` in any other terminal window."
    Process.wait
    

    Sources:

    • difference between both
    • propagation explanation

提交回复
热议问题