在bash中从键盘发送SIGINT到管道命令

时间:2012-10-05 19:44:31

标签: linux bash signals

如果在bash中我在命令行上运行a | b | c | d,然后按 ^ C ,哪个进程获取信号?

2 个答案:

答案 0 :(得分:11)

简而言之,他们都这样做。

设置管道时,shell会创建 process group ^ C 由内核的线路规则解释为用户请求中断当前在前台运行的进程组。向进程组发送SIGINT等信号会自动将信号传递给组中的所有进程。

答案 1 :(得分:3)

我更喜欢实验:

#!/bin/bash
# FILE /tmp/bla.sh
# trap ctrl-c and call ctrl_c()
trap ctrl_c INT

MY_ID=$1 # Identifier for messages

function ctrl_c() {
    echo >&2 "GOODBYE $MY_ID"
    exit
}

# This will continue until interrupted, e.g. if the input/output get closed
cat
# If we somehow got to the end
echo >&2 "grace $MY_ID"

链接它们,运行并打破它们

nitz@mars:~$ /tmp/bla.sh 1 | /tmp/bla.sh 2
^CGOODBYE 2
GOODBYE 1
0

正如你所看到的,两次执行都得到了中断信号,这意味着它们都会被杀死。此外,它们输出它们被杀死的顺序是随机的,例如:

nitz@mars:~$ /tmp/bla.sh 1 | /tmp/bla.sh 2 | /tmp/bla.sh 3 | /tmp/bla.sh 4
^CGOODBYE 2
GOODBYE 4
GOODBYE 1
GOODBYE 3