我有一个脚本,它从命名管道读取命令:
#! /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
以某种方式,脚本无法读取从管道中获取的所有字符串?如何阅读?
答案 0 :(得分: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
一旦使用此消耗模式的进程不止一个,则任何单个进程都会看到丢失的字符。