在没有读者的情况下尝试写时陷阱SIGPIPE

时间:2014-06-13 09:20:18

标签: linux bash signals named-pipes sigpipe

我正在尝试在Bash中的两个进程之间实现命名管道通信解决方案。

第一个进程将一些内容写入命名管道:

send(){
    echo 'something' > $NAMEDPIPE
}

第二个脚本应该像这样读取命名管道:

while true;do
  if read line < $NAMEDPIPE;do
      someCommands
  fi
done

请注意,以前使用传统命令

创建了命名管道
mkfifo $NAMEDPIPE

我的问题是读者脚本并不总是在运行,因此如果编写器脚本试图写入命名管道,它将保持阻塞状态,直到读者连接到管道。

我想避免这种行为,解决方法是捕获SIGPIPE信号。实际上,根据man 7,当试图在没有读卡器的管道中写入时,应该发送信号。所以我改变了我的红色功能:

read(){
    trap 'echo "SIGPIPE received"' SIGPIPE
    echo 'something' > $NAMEDPIPE
}

但是当我运行阅读器脚本时,脚本会被阻止,并且&#34; SIGPIPE收到&#34;不打印。

我是否误解了信号机制或者是否有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

这是我刚才制作的有趣代码。也许你可以参考这个:

#!/bin/bash

shopt -s extglob

NAMEDPIPE=/var/run/sr-pipe
RECEIVER_PID_FILE=/var/run/sr-receiver-pid

function sender_start {
    # Create named pipe.

    if [[ -e $NAMEDPIPE ]]; then
        echo "[Sender] Named pipe \"$NAMEDPIPE\" already exists."
    else
        echo "[Sender] Creating named pipe \"$NAMEDPIPE\"."
        mkfifo "$NAMEDPIPE" || {
            echo "Failed to create named pipe \"$NAMEDPIPE\"."
            exit 1
        }
    fi

    # Wait for receiver.

    echo "[Sender] Waiting for receiver."
    local PID
    until [[ -e $RECEIVER_PID_FILE ]] \
    && read PID < "$RECEIVER_PID_FILE" \
    && [[ $PID == +([[:digit:]]) ]] \
    && kill -s 0 "$PID" &>/dev/null; do
        sleep 1s
    done
    echo "[Sender] Receiver is [now] active."

    # Send signal.

    kill -s SIGPIPE "$PID"

    # Send messages.

    local SEND=''

    echo "[Sender] Now sending messages."
    while sleep 1s; do
        SEND=$RANDOM
        echo "[Sender] Sending $SEND."
        echo "$SEND" >&4
    done 4>"$NAMEDPIPE"
}

function receiver_start {
    echo "$BASHPID" > "$RECEIVER_PID_FILE"

    echo "[Receiver] Receiver is now active."

    local QUIT=false RECEIVE=false

    trap 'RECEIVE=true' SIGPIPE
    trap 'QUIT=true' SIGINT SIGTERM SIGHUP

    while [[ $QUIT == false ]]; do
        if [[ $RECEIVE == true ]]; then
            RECEIVE=false
            echo "[Receiver] Now receiving messages."
            while [[ $QUIT == false ]] && IFS= read -r -u 4 LINE; do
                echo "[Receiver] Received $LINE."
            done 4<"$NAMEDPIPE"
        fi
        sleep 1s
    done
}

if [[ $1 == send ]]; then
    sender_start
elif [[ $1 == receive ]]; then
    receiver_start
fi

在一个终端上我跑了这个:

# bash sender-receiver.sh send
[Sender] Named pipe "/var/run/sr-pipe" already exists.
[Sender] Waiting for receiver.
[Sender] Receiver is [now] active.
[Sender] Now sending messages.
[Sender] Sending 21524.
[Sender] Sending 1460.
[Sender] Sending 8352.
[Sender] Sending 4424.
...

另一方面,我得到了这个(更正):

# bash sender-receiver.sh receive
[Receiver] Receiver is now active.
[Receiver] Now receiving messages.
[Receiver] Received 21524.
[Receiver] Received 1460.
[Receiver] Received 8352.
[Receiver] Received 4424.
...

您可能可以在同一终端上的前台运行背景和接收器。