[英]Sending SIGINT from keyboard to piped commands in bash
如果在bash中我运行a | b | c | d
a | b | c | d
a | b | c | d
在命令行上然后按^ C ,哪个进程获取信号?
简而言之,他们都这样做。
在设置管道时,shell会创建一个进程组 。 ^ C由内核的线路规程解释为用户请求中断当前在前台运行的进程组。 将SIGINT
等信号发送到进程组会自动将信号传递给组中的所有进程。
我更喜欢实验:
#!/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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.