从命名管道读取错误

问题描述 投票:3回答:1

我有一个脚本,它从命名管道中读取命令:

#! /usr/bin/env bash
host_pipe="host-pipe"

#pipe for executing commands
[ -p "$host_pipe" ] || mkfifo -m 0600 "$host_pipe" || exit 1 
chmod o+w "$host_pipe"

set -o pipefail

while :; do
    if read -r cmd <$host_pipe; then
        if [ "$cmd" ]; then
            printf 'Running: %s \n' "$cmd"
        fi
    fi
done

我运行它并使用命令进行测试:

bash -c "echo 'abcdef' > host-pipe"
bash -c "echo 'abcdef' > host-pipe"
bash -c "echo 'abcdef' > host-pipe"
bash -c "echo 'abcdef' > host-pipe"

并获得奇怪的输出:

Running: abcdf 
Running: abcdef 
Running: abcde 
Running: abcdf 
Running: ace

以某种方式,脚本无法读取从管道获取的所有字符串?如何阅读?

bash pipe named-pipes
1个回答
3
投票

您必须具有一个以上运行的命名管道host-pipe的读取器,才能实现这一点。

检查脚本是否在后台或可能在另一个终端中运行第二个实例。

说明

您会发现bash将一次从管道发出1个字节的读取。如果您使用的是Linux,则可以strace您的脚本。这是摘录:

open("host-pipe", O_RDONLY|O_LARGEFILE) = 3
fcntl64(0, F_GETFD)                     = 0
fcntl64(0, F_DUPFD, 10)                 = 10
fcntl64(0, F_GETFD)                     = 0
fcntl64(10, F_SETFD, FD_CLOEXEC)        = 0
dup2(3, 0)                              = 0
close(3)                                = 0
ioctl(0, TCGETS, 0xbf99bfec)            = -1 ENOTTY (Inappropriate ioctl for device)
_llseek(0, 0, 0xbf99c068, SEEK_CUR)     = -1 ESPIPE (Illegal seek)
read(0, "a", 1)                         = 1
read(0, "b", 1)                         = 1
read(0, "c", 1)                         = 1
read(0, "d", 1)                         = 1
read(0, "e", 1)                         = 1
read(0, "f", 1)                         = 1
read(0, "\n", 1)                        = 1
dup2(10, 0)                             = 0
fcntl64(10, F_GETFD)                    = 0x1 (flags FD_CLOEXEC)
close(10)                               = 0

一旦使用该消耗模式的进程不止一个,任何单个进程都将看到丢失的字符。

© www.soinside.com 2019 - 2024. All rights reserved.