[英]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.