簡體   English   中英

在bash中從鍵盤發送SIGINT到管道命令

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM