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

pyt*_*hor 11 linux bash signals

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

use*_*342 13

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

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


Nit*_*itz 8

我更喜欢实验:

#!/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"
Run Code Online (Sandbox Code Playgroud)

拴住他们,跑动并打破他们

nitz@mars:~$ /tmp/bla.sh 1 | /tmp/bla.sh 2
^CGOODBYE 2
GOODBYE 1
0
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)